Search code examples
pythonpython-3.xpython-typingflake8pydantic

How to state, in Pydantic, that a staticmethod/classmethod returns an instance of the class in question?


I'm working in Python 3.7 and have something like this

class A(object):

  def __init__(self, value: int):
    self.value = value
  
  @classmethod
  def factory(cls, value: int) -> A:
    return A(value=value)

Yes, it's a contrived example, but I'm essentially trying to annotate the factory function to state that it returns an instance of A, however, this fails when I attempt to run the flake8 linter over the file as it complains that A isn't defined.

Is there some way to annotate this function such that the linter won't complain?


Solution

  • You can avoid this by annotating with 'A' instead:

    class A:
        @classmethod
        def factory(cls, value: int) -> 'A':
            ...
    

    Alternatively you can use __future__ annotations:

    from __future__ import annotations
    

    and keep annotating with A.