Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to get a named series of constants (enumeration) in Python? [duplicate]

Tags:

Just looking at ways of getting named constants in python.

class constant_list:     (A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3) 

Then of course you can refer to it like so:

constant_list.A_CONSTANT 

I suppose you could use a dictionary, using strings:

constant_dic = {     "A_CONSTANT" : 1,     "B_CONSTANT" : 2,     "C_CONSTANT" : 3,} 

and refer to it like this:

constant_dic["A_CONSTANT"] 

My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?

Thanks in advance.

like image 440
Bernard Avatar asked Oct 13 '08 06:10

Bernard


People also ask

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.

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.

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.

What is the point of enum in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.


2 Answers

For 2.3 or after:

class Enumerate(object):   def __init__(self, names):     for number, name in enumerate(names.split()):       setattr(self, name, number) 

To use:

 codes = Enumerate('FOO BAR BAZ') 

codes.BAZ will be 2 and so on.

If you only have 2.2, precede this with:

 from __future__ import generators   def enumerate(iterable):    number = 0    for name in iterable:      yield number, name      number += 1 

(This was taken from here)

like image 137
Tomalak Avatar answered Oct 29 '22 19:10

Tomalak


I find the enumeration class recipe (Active State, Python Cookbook) to be very effective.

Plus it has a lookup function which is nice.

Pev

like image 40
Simon Peverett Avatar answered Oct 29 '22 18:10

Simon Peverett