ruk·si

🐍 Python
Class Decorators

Updated at 2018-06-10 07:44

Class decorators themselves don't get passed to subclasses. But changes the decorators make might.

from typing import Type, TypeVar

T = TypeVar('T')

def spyglass(cls: Type[T]) -> Type[T]:
    for key, attribute in cls.__dict__.items():
        print(key, attribute)
    cls.secret = 'boo!'
    return cls

@spyglass
class Person:
    name: str = 'Unknown'
    age: int = 0

# => __module__ __main__
# => name Unknown
# => age 0
# => __dict__ <attribute '__dict__' of 'Person' objects>
# => __weakref__ <attribute '__weakref__' of 'Person' objects>
# => __doc__ None

assert Person.secret == 'boo!'

class Employee(Person):
    job_title: str = ''

# no printing, but the changes can be found in parent
assert Employee.secret == 'boo!'

Source

  • Fluent Python, Luciano Ramalho