Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use typing union in python? [duplicate]

Tags:

python

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)
like image 241
andy Avatar asked Oct 28 '25 01:10

andy


1 Answers

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

like image 56
bruno0 Avatar answered Oct 29 '25 18:10

bruno0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!