
On Sun, Feb 06, 2022 at 02:13:59AM +0400, Abdulla Al Kathiri wrote:
The “|” operator is another way of doing Union[Literal[“John], None] which is already supported in the new versions of Python. Correct me if I am wrong please. Maybe the types already use __or__ and __ror__ to sugar coat Union?
Type objects are objects, and their behaviour is controlled by their metaclass, just as instances are objects and their behaviour is controlled by their class. That means we can do this:
T = int | float type(T) <class 'types.UnionType'>
What we can't do is have instances behave differently according to context. There is no way to have the `|` operator behave differently in different contexts: value = 1 | 8 # return 9 T = 1 | 8 # return Literal[1, 8] L = [0, 1 | 8, 2] # what should | do inside a list? arr[:1 | 8] # what about after a colon in a slice?
Maybe if integers or strings or any other literal occurs after “:”, we could treat them slightly differently than what their actual __or__ and __ror__ would normally do?
Fortunately the Steering Council has said that syntax in annotations and syntax outside of annotations will remain the same. So any expression that you can write in an annotation will have the same meaning if you take it out and assign it to a named type. In other words, we can always refactor type hints by moving them out of the annotation: x: expression = value T = expression x: T = value And that is excellent. -- Steve