Python Glossary Русский

Python 3.6+enumfunction

enum.Enum._missing_()

handling

The _missing_() class method is called when a value is not found in the enumeration (through Enum(value)).

Syntax

@classmethod
def _missing_(cls, value): ...

It fires only on lookup by value — Enum(value); name lookup via Enum['NAME'] and plain attribute access never reach it. Return a member of the same enum or None (in which case the usual ValueError is raised); anything else turns into a TypeError. The typical use is lenient aliasing: match a string case-insensitively, or hand back a default member instead of an exception.

Examples

from enum import Enum
class Color(Enum):
    RED = 1; GREEN = 2
    @classmethod
    def _missing_(cls, value):
        return cls.RED  # значение по умолчанию
Color(99) # → <Color.RED: 1>
Color(0) # → <Color.RED: 1>
Color(1) # → <Color.RED: 1>

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy