Author kj
Recipients gvanrossum, kj, levkivskyi
Date 2020-11-01.15:32:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
Union type expressions added in PEP 604 throw an error when both operands are GenericAlias objects.

Eg the following works::

int | list[str]

The following throws TypeError::

list[int] | dict[float, str]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'types.GenericAlias' and 'types.GenericAlias'

I have submitted a PR to fix this. Coincidentally, it also fixes the fact that union expressions weren't de-duplicating GenericAlias properly.

>>> list[int] | int | list[int]
list[int] | int | list[int]

For non-GenericAlias type expressions, the new code shouldn't be much slower. Rich compare is only used for GenericAlias objects. This isn't very scientific, but 

python -m timeit "int | str | float"

# original
1000000 loops, best of 5: 295 nsec per loop

# purely rich compare
1000000 loops, best of 5: 344 nsec per loop

# check  for GenericAlias and rich compare only for that
1000000 loops, best of 5: 297 nsec per loop
Date User Action Args
2020-11-01 15:32:10kjsetrecipients: + kj, gvanrossum, levkivskyi
2020-11-01 15:32:10kjsetmessageid: <>
2020-11-01 15:32:10kjlinkissue42233 messages
2020-11-01 15:32:10kjcreate