pythontype-hinting

Pipe notation for more than two types in a type hint


I am trying:

def foo(x: int | float | str):
    pass
foo(0)

and get the error:

TypeError: unsupported operand type(s) for |: 'type' and 'type'

Is it possible to use more than two types with pipe notation or I have to write Union?


Solution

  • Syntactic sugar like this to represent union types wasn't added until 3.10 with the introduction of PEP 604. Update to 3.10+ or use typing.Union.