Home > Net >  What does Union from typing module in Python do?
What does Union from typing module in Python do?

Time:04-27

I was looking the implementation of ResNet deep learning architecture in PyTorch from git-hub. At line 167, inside the initializer of another class definition which defines ResNet and is also named ResNet, I saw the code below:

block: Type[Union[BasicBlock, Bottleneck]],

BasicBlock and Bottleneck are two classes defined before line 167. When I looked up for what Type and Union do, as far as I understood it says that block could be either of BasicBlock or Bottleneck. block itself was passed to a function named _make_layer which is defined at line 223 and is a method of ResNet class and I wonder how _make_layer know how the passed argument is either BasicBlock or Bottleneck?

When someone is making an instance of ResNet class, should they pass an object of BasicBlock or Bottleneck? and is this how _make_layer knows what it got as its argument? Then why do we need to use Union?

CodePudding user response:

Union in this case means both types are allowed.

Remember typing in python isn't enforced. It's only checked. So you can still pass whatever you want and it might work. However, a type checker like pyright or mypy will alert you to the discrepancy.

CodePudding user response:

To reinforce the previous answer. Python couldn't care less about types. They are ignored completely. Their sole purpose is for linters.

IDE's like PyCharm also have linters built into them. PyCharm has caught numerous bugs for me: "you said that function was supposed to take a two strings, but you're passing it an integer and a string". Python itself just doesn't care.

  • Related