(Python 类型提示)如何将当前定义的类型指定为方法的返回类型?

(Python type hints) How to specify type being currently defined as the returned type from a method?

我想指定(作为类型提示)当前定义的类型为方法中的 return 类型。

这是一个例子:

class Action(Enum):
    ignore = 0
    replace = 1
    delete = 2

    @classmethod
    # I would like something like
    # def idToObj(cls, elmId: int)->Action:
    # but I cannot specify Action as the return type
    # since it would generate the error
    # NameError: name 'Action' is not defined
    def idToObj(cls, elmId: int):
        if not hasattr(cls, '_idToObjDict'):
            cls._idToObjDict = {}
            for elm in list(cls):
                cls._idToObjDict[elm.value] = elm

        return cls._idToObjDict[elmId]

理想情况下,我希望指定类似

的内容
def idToObj(cls, elmId: int)->Action:

谢谢。

官方提到了这个案例type hints PEP:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

为了解决这个问题,我们写道:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

你的情况是:

def idToObj(cls, elmId: int)->'Action':
    pass  # classmethod body