Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum name in Python without class name

I would like to create my own enum. This will have names but no values. When calling this enum it should always return the name.

from enum import Enum

class myEnum(Enum):
    def __repr__(self):
        return self.name

my_enum = myEnum('enum', ['a', 'b'])

With:

print(my_enum.a) 

it will returns a. That's ok.

But using this in a class:

class T():
    def do_something(self):
        print(my_enum.a)

With:

T().do_something()

will return enum.a

Goal is this will always return a.

like image 907
Nico W. Avatar asked Nov 14 '18 10:11

Nico W.


People also ask

How do I get the enum key in Python?

To get an enum name by value, pass the value to the enumeration class and access the name attribute, e.g. Sizes(1). name . When the value is passed to the class, we get access to corresponding enum member, on which we can access the name attribute.

How do you print an enum in Python?

The __str__() method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object. Now you can get the value of the enum directly, without accessing the value attribute on the enum member. You can also use square brackets to access enum members.

What are enumerations in Python?

An Enum is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful repr() , grouping, type-safety, and a few other features. As you can see, creating an Enum is as simple as writing a class that inherits from Enum itself.

What is Auto in enum Python?

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.


1 Answers

If When calling this enum it should always return the name means when a string is required then you can add this method to the myEnum class:

def __str__(self):
    return self.name
like image 54
Marco Avatar answered Oct 08 '22 14:10

Marco