Python Glossary Русский

Python 3.11+enumfunction

enum.global_str

globalization

The __str__ function for members of a globalized enum (bare member name).

Syntax

enum.global_str(member)

You essentially never call this yourself: it is plumbing for the @global_enum decorator, which copies members into the module's global namespace (think re.IGNORECASE) and swaps __str__ for this function. The point is that print() and f-strings show the exact name the constant is reachable by in the module, not the ClassName.MEMBER form. As a side effect str() and repr() of such a member no longer agree, which is intended.

Examples

import enum
print(callable(enum.global_str))   # → True
Color = enum.Enum('Color', 'RED GREEN')
print(str(Color.RED))   # → Color.RED
print(enum.global_str(Color.RED))   # → RED
Color.__str__ = enum.global_str
print(str(Color.GREEN))   # → GREEN
print(repr(Color.GREEN))   # → <Color.GREEN: 2>

See also

Open in the full glossarydocs.python.orgReport an inaccuracy