类型错误: | 不支持的操作数类型:“type”和“NoneType”

jet*_*een 7 python typing nonetype

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
Run Code Online (Sandbox Code Playgroud)

类型错误: | 不支持的操作数类型:“type”和“NoneType”

Python 3.9

我认为问题是使用最新版本的python,如何解决。

我尝试使用“或”,但没有帮助

Hol*_*way 17

str | None仅 3.10 或更高版本支持语法。使用

from typing import Optional
name: Optional[str] = None
Run Code Online (Sandbox Code Playgroud)

对于右侧不是None或者有两种以上类型的情况,您可以使用Union

from typing import Union
foo: Union[str, int, float] = "bar"
Run Code Online (Sandbox Code Playgroud)

  • @PoneyUHC,好点,我也为该案例添加了一个示例。值得注意的是,“Optional[T]”是“typing”模块中“Union[T, None]”的别名,而不是它自己的类型。 (4认同)
  • `Optional` 是一个很好的类型,并且是跨多种语言广为人知的类型,对此 +1 然而,Python <= 3.9 中的 `|` 的准确等价物是更一般的 `Union[type1, type2]`案件 (2认同)