1

All classes need to be defined before they can be used as a type hint. To get around it in some scenarios, the __future__ import is recommended. That's why the following code works fine (in Python 3.7):

from __future__ import annotations


class Person:
    def get_relative(name: str) -> Person:
        ...

Without the __future__ import it would raise a NameError. But this code works fine too:

from __future__ import annotations


class Person:
    def get_relative(name: BlahBlahTypoWhatever) -> Person:
        ...

I expected something like NameError: name 'BlahBlahTypoWhatever' is not defined. Is this an expected behavior?

Jeyekomon
  • 2,878
  • 2
  • 27
  • 37

1 Answers1

3

Python itself does no type checking whatsoever, so it won't raise any error about wrong types.

The annotations future is simply implicitly changing all annotations to strings, i.e. this is equivalent:

from __future__ import annotations

def foo(bar: Baz): pass
def foo(bar: 'Baz'): pass

Since your annotation is a string now, and Python doesn't do anything with it, there's absolutely no resolution of that name going on at any point, so it doesn't raise any errors.

deceze
  • 510,633
  • 85
  • 743
  • 889