CONFIG.SYS
  • ALL_POSTS.BAT
  • ABOUT.EXE

How to forward reference a type in python - Thu, Mar 24, 2022

How to forward reference a type in python

Recently I refactored the test project for this blog. I wanted to introduce a more general method of testing referenced pages. Therefore I created a general data type called Page with the following definition:

class Page(BaseModel):
    name: Optional[str]
    url: Optional[str]
    link_text_pattern: Optional[str]
    keyword_patterns: Optional[List[str]]
    pages: Optional[List[Page]]

After finishing the definition the IDE complained about an Unresolved reference 'Page' in the last line. Coming from a Java background I wondered why this error occurred, since similar code is valid in Java.
After some research I learned that in Python a type may not be used before its definition. Since the definition of the type Page contains the type itself, the code was not compilable. The solution to the problem was to add the following import:

from __future__ import annotations

So how exactly did this import do to solve the problem. First of all the __future__ module is a valid python module with the following purpose:

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes […]

Or in other words, the forward reference of the type Page will be standard in a forthcoming release of python. And since it is not yet available, I had to import annotations from the future module so that the compiler would apply it now. The exact description of the new feature can be found on the peps specification .

Now the key here is, that the __future__ statements ease the migration to new versions, since their usage is easy to find.

Back to Home


21st century version | © Thomas Reuhl 2020-2022 | Disclaimer | Built on Hugo

Linkedin GitHub