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.
By definition, the enumeration member values are unique. However, you can create different member names with the same values.
By convention, enumeration names begin with an uppercase letter and are singular. The enum module is used for creating enumerations 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.
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.
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)
I find the enumeration class recipe (Active State, Python Cookbook) to be very effective.
Plus it has a lookup function which is nice.
Pev
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With