Python Glossary Русский

Python 3.11+enumterm

enum.property

attributes

An enum-aware version of the built-in property: it lets a member attribute share its name with a member — that is how name and value work.

Syntax

@enum.property
def attr(self): ...

Thanks to it an Enum may have members called name and value: Field.name is a member and Field.name.name is its name. The property and the same-named member must live in different classes: the property in the base Enum, the member in the subclass. Accessed on the class instead of a member, enum.property raises AttributeError, whereas a plain property would return the property object. For your own computed member attributes a plain @property is enough; enum.property matters when a name may clash with a member.

Examples

from enum import Enum
class Field(Enum):
    name = 1
    value = 2
print(Field.name, Field.name.name, Field.value.value)  # → Field.name name 2
# Python 3.12+
import enum
class Planet(enum.Enum):
    EARTH = (5.97e24, 6.37e6)
    @enum.property
    def mass(self):
        return self.value[0]
print(Planet.EARTH.mass)  # → 5.97e+24
try:
    Planet.mass
except AttributeError as e:
    print(e)  # → <enum 'Planet'> has no attribute 'mass'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy