When using a class method as a factory method, how do we do type hinting for the output?

Viewed 20

In Python,

class Example:
  @classmethod
  def build_class_instance(cls, fixed_inputs:List[str],unchanged_args):List[str]:
      new_vars = f(fixed_inputs)
      return Example(new_vars,unchanged_args)

The problem now seems that for the output, if I write -> Example, my IDE complains about it...

What should I write?

1 Answers

When the interpreter gets to the type annotation, the Example class is not yet fully defined. You can use a forward reference by putting the class name in quotes like this:

class Example:
    @classmethod
    def build_class_instance(cls) -> 'Example':
        return Example()

EDIT:

As @ShadowRanger pointed out, you can also make use of this early on in your module:

from __future__ import annotations

That way, you don't even need the quotes.

Related