Home > Net >  Python 3: Add Enum attributes to class scope
Python 3: Add Enum attributes to class scope

Time:08-13

In Python 3.10 is there a way to add the attributes (RED in this case) to the scope of a class (MyClass in this case) like this:


    class Color(Enum):
        RED = 1
    class MyClass():
        def myMethod(self, t):
            return t is RED # instead of return t is Color.RED

Without

  1. adding RED to the global scope e.g. like this: globals().update(Color.__members__)
  2. adding some initialization code to every class method (e.g. like the above; but locals() cannot be updated in that fashion anyway as far as I know)

CodePudding user response:

You must use this sintax:

enum_class.enum => Color.RED


I also found this in Python's doc:

Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently)

Color.BLUE == 2 => False


You must use IntEnum.

from enum import IntEnum

class Color(IntEnum):
    RED = 1
    
class MyClass():
    def myMethod(self, t):
        return Color.RED == 1 # Use 'enum_class.enum' to access to your attribute

print(MyClass().myMethod(1)) # True

CodePudding user response:

This is the pythonic way:

class Color(Enum):
    RED = 1

class MyClass():

    RED = Color.RED

    def my_method(self, t):
        return t is self.RED

Also, you can make my_method a @classmethod.

When the RED attribute is bound to the class like this, it also plays nicely with inheritence. E.g. subclasses can override it.

The following is more in line with your question, yet less recommended IMO:

class Color(Enum):
    RED = 1

RED = Color.RED

class MyClass():
    def my_method(self, t):
        return t is RED
  • Related