pythontype-hinting

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


I would like to specify (as a type hint) the currently defined type as the return type from a method.

Here's an example:

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]

Ideally I would have liked to specify something like

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

Thank you.


Solution

  • This case is mentioned in official 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
    

    To address this, we write:

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

    In your case It would be:

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