Question:
Before 3.10, I was usingUnion
to create union parameter annotations:TypeError: unsupported operand type(s) for |: ‘str’ and ‘type’
Is this not supported?
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):
from __future__ import annotations class Vector: def __mul__(self, other: Vector | float): ...
Make the whole type a string (effectively the same as deferring evaluation):
class Vector: def __mul__(self, other: "Vector | float"): ...
Keep using the
Union
:from typing import Union class Vector: def __mul__(self, other: Union["Vector", float]): ...
You can see further discussion, without a resolution as yet, on this bug.
If you have better answer, please add a comment about this, thank you!