1

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?

MOON
  • 2,516
  • 4
  • 31
  • 49
  • I think you should review what type hints are and how they work generally. While the link doesn't explicitly talk about how `typing.Union` works in particular, it seems to me that you have a conceptual misunderstanding here. I'd also recommend checking out the official documentation. – ddejohn Apr 26 '22 at 16:56
  • @ddejohn If you know a concept, it's easy to ask for it, but it's mostly much harder to ask in the opposite direction, see also [how to use typing union in python?](https://stackoverflow.com/q/58038940/2932052) – Wolf Apr 26 '22 at 17:51

2 Answers2

2

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.

Paul H
  • 65,268
  • 20
  • 159
  • 136
1

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.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22