2

Python 3.5 introduced type hints which allow one to write the following:

from typing import Union

answer: Union[int, str] = 42
answer = '42'

documentation: https://docs.python.org/3/library/typing.html#typing.Union

I think I understand the naive meaning of the above code. In particular, it means that the variable answer has been given a type hint, which says that it is supposed to be of the Union type with type parameters int and str, which in turn means that it is supposed to be either int or str.

What I do not understand, however, are the formal Python language rules around defining and using classes with type parameters in square brackets.

Can someone explain it?

2
  • Are you saying Union(int, str) makes more sense? Can you explain why? () is only reserved for tuples, expression grouping, and function calls. Commented Mar 8, 2018 at 16:24
  • No, I am not saying that. I am asking what the rules are around using this syntax and how can one define a class which would accept such type parameters. Commented Mar 8, 2018 at 16:26

2 Answers 2

4

Like any other use of square brackets, Union[int, str] is implemented by Union.__getitem__((int, str)). In this case, Union is an instance of the class _Union which defines __getitem__. You don't really need to know those details to use the class.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, so a metaclass is involved! Thanks for the explanation! It makes sense I guess, but I did not realize it is possible to use metaclasses for this purpose. I thought that some new syntax was introduced into the language.
I'll update the answer; there is a metaclass involved, but not for this particular bit. Union is actually an instance of the class _Union which implements __getitem__.
Thanks for the correction. The basic principle remains, I think, the same, i.e. no new language syntax is involved, but the existing language features are used to implement the classes which accept type parameters in the square brackets.
1

Where you use [] it is calling the __getitem__ method. The metaclass of the Union type has a __getitem__ method. When you call Union[int, str] you are calling that __getitem__ method passing a tuple, containing int and str. You can see this in the typing.py file in the Python library.

1 Comment

Thanks, the possibility to use metaclass is the important piece of information that I was missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.