Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the common practice for enums in Python? [duplicate]

Tags:

python

enums

Possible Duplicate:
How can I represent an 'enum' in Python?

What's the common practice for enums in Python? I.e. how are they replicated in Python?

public enum Materials {     Shaded,     Shiny,     Transparent,     Matte } 
like image 710
Joan Venge Avatar asked Mar 31 '09 20:03

Joan Venge


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

What are enums used for in Python?

Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.

Can enum have two same values Python?

By definition, the enumeration member values are unique. However, you can create different member names with the same values.

Is enum hashable Python?

Use Enum Members in DictionariesPython enumerations are hashable. This means you can use the enumeration members in dictionaries.


2 Answers

class Materials:     Shaded, Shiny, Transparent, Matte = range(4)  >>> print Materials.Matte 3 
like image 155
Van Gale Avatar answered Oct 05 '22 00:10

Van Gale


I've seen this pattern several times:

>>> class Enumeration(object):         def __init__(self, names):  # or *names, with no .split()             for number, name in enumerate(names.split()):                 setattr(self, name, number)  >>> foo = Enumeration("bar baz quux") >>> foo.quux 2 

You can also just use class members, though you'll have to supply your own numbering:

>>> class Foo(object):         bar  = 0         baz  = 1         quux = 2  >>> Foo.quux 2 

If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.

like image 42
Ben Blank Avatar answered Oct 05 '22 00:10

Ben Blank