with python3.6 reaching end of life, there is no need for this
A backport of __future__ annotations to python<3.7.
pip install future-annotations
Include the following encoding cookie at the top of your file (this replaces the utf-8 cookie if you already have it):
# -*- coding: future_annotations -*-And then write python3.7+ forward-annotation code as usual!
# -*- coding: future_annotations -*-
class C:
@classmethod
def make(cls) -> C:
return cls()
print(C.make())$ python3.6 main.py
<__main__.C object at 0x7fb50825dd90>
$ mypy main.py
Success: no issues found in 1 source filefuture-annotations also includes a cli to show transformed source.
$ future-annotations-show main.py
# ****************************** -*-
class C:
@classmethod
def make(cls) -> 'C':
return cls()
print(C.make())future-annotations has two parts:
- A utf-8 compatible
codecwhich performs source manipulation- The
codecfirst decodes the source bytes using the UTF-8 codec - The
codecthen leverages tokenize-rt to rewrite annotations.
- The
- A
.pthfile which registers a codec on interpreter startup.
in setups (such as aws lambda) where you utilize PYTHONPATH or sys.path
instead of truly installed packages, the .pth magic above will not take.
for those circumstances, you'll need to manually initialize future-annotations
in a non-annotations wrapper. for instance:
import future_annotations
future_annotations.register()
from actual_main import main
if __name__ == '__main__':
raise SystemExit(main())