Python etc / types.DynamicClassAttribute

Published: 08 October 2020, 18:00

types.DynamicClassAttribute is a decorator that allows having a @property that behaves differently when it’s called from the class and when from the instance.

from types import DynamicClassAttribute

class Meta(type):
    def hello(cls):
        return f'hello from Meta ({cls})'

class C(metaclass=Meta):
    def hello(self):
        return f'hello from C ({self})'

# "hello from Meta (<class '__main__.C'>)"

# 'hello from C (<__main__.C object ...)'

Practically, it is used only in enum to provide name and value properties for instances while still allowing to have name and value class members:

import enum

class E(enum.Enum):
    value = 1

# <E.value: 1>

# 1