新的联合速记表示“| 不支持的操作数类型:'str' 和 'type'”

ggh*_*voc 24 python type-hinting python-typing python-3.10

在3.10之前,我使用的Union是创建union参数注释:

from typing import Union

class Vector:
    def __mul__(self, other: Union["Vector", float]):
        pass
Run Code Online (Sandbox Code Playgroud)

现在,当我使用新的 union 速记语法时:

class Vector:
    def __mul__(self, other: "Vector" | float):
        pass
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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

Is this not supported?

jon*_*rpe 28

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:

  1. Defer evaluation (see PEP 563):

    from __future__ import annotations
    
    class Vector:
        def __mul__(self, other: Vector | float): ...
    
    Run Code Online (Sandbox Code Playgroud)
  2. Make the whole type a string (effectively the same as deferring evaluation):

    class Vector:
        def __mul__(self, other: "Vector | float"): ...
    
    Run Code Online (Sandbox Code Playgroud)
  3. Keep using the Union:

    from typing import Union
    
    class Vector:
        def __mul__(self, other: Union["Vector", float]): ...
    
    Run Code Online (Sandbox Code Playgroud)

您可以看到有关此错误的进一步讨论,但尚未解决。