__annotations__Easy Examples

Dictionary of type annotations for a function or class

Accessing __annotations__

How to access and use __annotations__.

python
# __annotations__ holds type hints
class Config:
    debug: bool = True
    port: int = 8080
    host: str = "localhost"

print(Config.__annotations__)

def greet(name: str, times: int = 1) -> str:
    return name * times

print(greet.__annotations__)

__annotations__ is a special attribute that dictionary of type annotations for a function or class.

__annotations__ in practice

Using __annotations__ in everyday code.

python
# More __annotations__ examples
print("__annotations__ is a special Python attribute")

# Every object has certain dunder attributes
obj = object()
attrs = [a for a in dir(obj) if a.startswith("__")]
print(f"object has {len(attrs)} dunder attributes")

Understanding __annotations__ helps you introspect and debug Python objects.

Want to try these examples interactively?

Open Easy Playground