4

I found the following code:

def get_iterator_from_config(config: dict, data: dict):
    iterator_config = config['dataset_iterator']
    iterator: Union[DataLearningIterator, DataFittingIterator] = from_params(iterator_config,data=data)
    return iterator

why iterator has colon and then Union? Does it mean the type of iterator is union?why can't just use:

iterator= from_params(iterator_config,data=data)
andy
  • 1,951
  • 5
  • 16
  • 30
  • I thought this was invalid syntax, but after researching it, you can actually use it, probably for readability purposes, so the type of iterator is clearly readable from the variable definition. Because of python's "duck typing" this is sometimes needed. – kuco 23 Sep 21 '19 at 09:31

1 Answers1

11

It's just type hinting, and is used as a means to indicate what type the parameter might be. Union[DataLearningIterator, DataFittingIterator] means that it's either a DataLearningIterator or a DataFittingIterator.

You're right that it's not needed, but it's probably used for readability, i.e. to indicate which types we expect the iterator to be.

For details, please see this: https://docs.python.org/3/library/typing.html

bruno0
  • 176
  • 1
  • 4