1
from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str | None = None
    unit_price: float
    quantity_on_hand: int = 0

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

Python 3.9

I think the problem is using the latest version of python, how to solve it.

i tried use 'or' but it didn't help

0

1 Answer 1

10

str | None syntax is only supported in 3.10 or later. Use

from typing import Optional
name: Optional[str] = None

For cases where the right hand side isn't None or there are more than two types, you can use Union

from typing import Union
foo: Union[str, int, float] = "bar"
2
  • 1
    Optional is a nice type, and is a widely known type across multiple languages, +1 for that However, an accurate equivalent to | in Python <= 3.9 would be Union[type1, type2] in a more general case
    – PoneyUHC
    Jul 18 at 13:41
  • 3
    @PoneyUHC, good point, I've added an example for that case as well. Worth noting that Optional[T] is an alias for Union[T, None] in the typing module, not its own type.
    – Holloway
    Jul 18 at 14:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.