Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice print of python Enum

Assume I have the following:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

As the output of print(Color), I want to see:

The colors are:
- RED
- GREEN
- BLUE

I've tried:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

    @classmethod
    def __str__(self):
        res = "The colors are:\n"
        for g in set(map(lambda c: c.name, Color)):
            res += '- ' + g + '\n'
        return res

But it only works as print(Color(1)). How can I have it working when using print(Color)?

like image 865
Dror Avatar asked Nov 20 '18 16:11

Dror


People also ask

How do I print an enum in Python?

We can access the enum members by using the dot operator(.) with the enum class name. repr() : The repr() method used to print enum member. type(): This is used to print the type of enum member.

Should I use enums in Python?

Use it anywhere you have a canonical source of enumerated data in your code where you want explicitly specified to use the canonical name, instead of arbitrary data. For example, if in your code you want users to state that it's not "Green" , "green" , 2, or "Greene" , but Color. green - use the enum.

What is Auto () in Python?

With the help of enum. auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.

Should enums be capitalized Python?

By convention, enumeration names begin with an uppercase letter and are singular. The enum module is used for creating enumerations in Python.

How to get the value of an enum in Python?

Use the value attribute in the enum if you want to get value in Python. Simple example code has defined the enum and prints the value. from enum import Enum class D (Enum): x = 100 y = 200 print (D.x.value) You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation.

How to print enum members as string type in Python?

To print enum members as string type you can use str () function. The default type of an enumeration member is the enumeration it belongs to: # python3 create_enum.py Before: <enum 'errorcode'> After: <class 'str'> Similarly to print Enum members as Integers we can use int () function but we must also use IntEnum subclass instead of Enum

How to print an enum as an iterable list?

We can print the enum as an iterable list. In the below code we use a for loop to print all enum members. Example import enum # Using enum class create enumerations class Days(enum.Enum): Sun = 1 Mon = 2 Tue = 3 # printing all enum members using loop print ("The enum members are : ") for weekday in (Days): print(weekday) Output

How do you iterate an enum in Python 3?

# python3 create_enum.py repr representation: <errorcode.success: 0> Enumerations support iteration, in definition order. Iterating over the enum class produces the individual members of the enumeration. The output from this script shows the members are produced in the order they are declared in the class definition.


1 Answers

To override printing of the class, you could define __str__ on the metaclass:

from enum import Enum, EnumMeta

class MyEnumMeta(EnumMeta):
    def __str__(cls):
        lines = [f"The {cls.__name__.lower()}s are:"]
        for member in cls:
            lines.append(f"- {member.name}")
        return '\n'.join(lines)

class Color(Enum, metaclass=MyEnumMeta):
    RED = 1
    GREEN = 2
    BLUE = 3

Demo:

>>> Color
<enum 'Color'>
>>> print(Color)
The colors are:
- RED
- GREEN
- BLUE
>>> Color.RED
<Color.RED: 1>
>>> print(Color.RED)
Color.RED

The class name is discovered:

>>> class Animal(Enum, metaclass=MyEnumMeta): 
...     cat = 'meow' 
...     dog = 'woof' 
...     badger = 'grrr' 
...
>>> print(Animal)
The animals are:
- cat
- dog
- badger
like image 52
wim Avatar answered Nov 09 '22 23:11

wim