Python Annotations
Python Annotations
**************************
author:
Larry Hastings
Abstract
^^^^^^^^
class Base:
a: int = 3
b: str = 'abc'
class Derived(Base):
pass
print(Derived.__annotations__)
This will print the annotations dict from "Base", not "Derived".
Your code will have to have a separate code path if the object you're
examining is a class ("isinstance(o, type)"). In that case, best
practice relies on an implementation detail of Python 3.9 and before:
if a class has annotations defined, they are stored in the class's
"__dict__" dictionary. Since the class may or may not have
annotations defined, best practice is to call the "get" method on the
class dict.
To put it all together, here is some sample code that safely accesses
the "__annotations__" attribute on an arbitrary object in Python 3.9
and before:
if isinstance(o, type):
ann = o.__dict__.get('__annotations__', None)
else:
ann = getattr(o, '__annotations__', None)
Note that some exotic or malformed type objects may not have a
"__dict__" attribute, so for extra safety you may also wish to use
"getattr()" to access "__dict__".
If you're using Python 3.9 or older, or if for some reason you can't
use "inspect.get_annotations()", you'll need to duplicate its logic.
You're encouraged to examine the implementation of
"inspect.get_annotations()" in the current Python version and follow a
similar approach.
* **PEP 604** union types using "|", before support for this was added
to Python 3.10.
"__annotations__" Quirks
========================
print(foo.__annotations__)