Before 3.10, I was using Union
to create union parameter annotations:
JavaScript
x
6
1
from typing import Union
2
3
class Vector:
4
def __mul__(self, other: Union["Vector", float]):
5
pass
6
Now, when I use the new union shorthand syntax:
JavaScript
1
4
1
class Vector:
2
def __mul__(self, other: "Vector" | float):
3
pass
4
I get the error:
TypeError: unsupported operand type(s) for |: ‘str’ and ‘type’
Is this not supported?
Advertisement
Answer
The fact that it’s being used as a type hint doesn’t really matter; fundamentally the expression "Vector" | float
is a type error because strings don’t support the |
operator, they don’t implement __or__
. To get this passing, you have three options:
Defer evaluation (see PEP 563):
JavaScript151from __future__ import annotations
2
3class Vector:
4def __mul__(self, other: Vector | float):
5
Make the whole type a string (effectively the same as deferring evaluation):
JavaScript131class Vector:
2def __mul__(self, other: "Vector | float"):
3
Keep using the
Union
:JavaScript151from typing import Union
2
3class Vector:
4def __mul__(self, other: Union["Vector", float]):
5
You can see further discussion, without a resolution as yet, on this bug.