Search code examples
pythonpython-typing

Python type hints for types not yet defined


How do I provide type hints for an alternative constructor for a class? For example if I have a method like this converting something to my new class,

class MyClass:
    @classmethod
    def from_string(cl: Type[????], s: str) -> ????:
        p, q = some_function(s)
        return cl(p, q)

what should I write for ????? It should by nature just be MyClass, but that variable is not defined yet at the time when the method definition is executed.


Solution

  • As PEP484 states, you can use strings as hints where the corresponding type is undefined at the time the type hint is read, but will be available later. This includes using strings as parts of type hints. Your code would therefore simply read

    class MyClass:
        @classmethod
        def from_string(cl: Type['MyClass'], s: str) -> 'MyClass':
            p, q = some_function(s)
            return cl(p, q)
    

    but actually, if your cl is not MyClass, the return value will be different, so better use a type variable like this:

    ParametersT = TypeVar("ParametersT", bound="Parameters")
    class Parameters (
            NamedTuple("Parameters", [
                ("n_steps", halfyears),
            ])):
        @staticmethod
        def from_ns(ns: Namespace) -> 'Parameters':
            return Parameters(**vars(ns))