Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum converter in python

Tags:

python

enums

I have an enum

class Nationality:
        Poland='PL'
        Germany='DE'
        France='FR'
        ...
        Spain='ES'

I have 2 prototypes of methods:

# I want somethink like in c#        
def convert_country_code_to_country_name(country_code):
        print Enum.Parse(typeof(Nationality),country_code)

#this a second solution ,but it has a lot of ifs

def convert_country_code_to_country_name(country_code):
        if country_code=='DE':
                print Nationality.Germany #btw how to print here 'Germany', instead 'DE'

This is how I want call this method:

convert_country_code_to_country_name('DE') # I want here to  print 'Germany'

How to implement it in python?

like image 679
user278618 Avatar asked Feb 24 '11 12:02

user278618


People also ask

How to convert enum to string in Python?

How to convert enum to string in python To print an enum member as a string we use the class and member name. In this example, we have enum class name FRUITS and have three members (APPLE = 1,ORANGE = 2,GRAPES = 3). We are printing enum members as FRUITS.APPLE by print () statement.

What is enumeration in Python?

In this tutorial, we will look into different methods of using or implementing the enum in Python. The enum or enumeration is a special type of class representing a set of named constants of numeric type. Each named constant in the enum type has its own integer value, which depends on the set’s named constant position.

How to display the name of the enum member in Python?

3. “ name ” keyword is used to display the name of the enum member. 4. Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. 1. By value :- In this method, the value of enum member is passed. 2. By name :- In this method, the name of enum member is passed.

How to iterate enum in Python?

Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. 1. By value :- In this method, the value of enum member is passed.


1 Answers

The best solution would be to create a dictionary right from the start. Your enum doesn't make sense in Python, its just unnecessarily complex. It looks like you are trying to write Java code, which is quite the opposite of what Python code is supposed to look like.

like image 127
nikow Avatar answered Oct 05 '22 03:10

nikow