Name not defined in type annotation [duplicate]

You have a forward declaration; functions (to be bound as methods) are created before the class is, so the name Vector doesn’t yet exist. Only when all of the class body has been executed, can Python create the class object and bind the name Vector to it.

Simply use a string with the name instead:

class Vector:
     # Various irrelevant implementation details
     def __add__(self, other: 'Vector') -> 'Vector':
        # More implementation details....

This doesn’t affect how your IDE sees the declaration; strings are looked up once the whole module is loaded, and are resolved as a valid Python expression in the current context. Since the class Vector exists once the whole module is loaded, the string 'Vector' can properly be converted to the class object.

Also see the specification on forward references:

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.

[…]

The string literal should contain a valid Python expression […] and it should evaluate without errors once the module has been fully loaded.

As of Python 3.7 you can make all annotations in a given module behave like forward annotations (without enclosing them in a string literal), by adding the from __future__ import annotations directive at the top of the module. It was originally planned for this to be the default in Python 3.10 and up, but this decision has now been deferred indefinitely. See PEP 563 — Postponed Evaluation of Annotations for details. Note that outside of annotations you may still need to use forward reference syntax (string literals), e.g. in a type alias (which is a regular variable assignment as far as Python is concerned).

Leave a Comment