0

I have a problem with python type annotations when a type is not declared at the point in file. Especially I have the problem when a class has a function that returns an instance of the class:

class Foo:
    def clone(self) -> Foo:
        return Foo()

results at runtime (not when checking with mypy) in an error:

NameError: name 'Foo' is not defined
allo
  • 3,955
  • 8
  • 40
  • 71

1 Answers1

1

Add at the beginning of the file the line

from __future__ import annotations

See here for a related question.

Luis G.
  • 161
  • 4
  • I wonder if it's better to use `__future__` or strings. But why does python itself evaluate the annotations anyway? I am confused, why the linter doesn't have the problem and the interpreter, which should ignore the annotations, raises an exception. – allo Aug 08 '22 at 19:35
  • 1
    This is a great question. Here you have the long answer: https://adamj.eu/tech/2021/05/15/python-type-hints-future-annotations/ The short answer is that, ignoring compatibility issues between python versions, it is better using types insted of strings. Why? Because turning them into strings is a workaround, you could put any stuff inside the string and you would now get an error. Python evaluates the type hints to assure they exist. There a deeper reasons that I won't tell in a comment. If you are curious read the link a attached. – Luis G. Aug 08 '22 at 19:58