Python now has an Enum type (new in 3.4 with PEP 435, and alse backported), and while namespaces are a good thing, sometimes Enums are used more like constants, and the enum members should live in the global (er, module) namespace.
So instead of:
Constant(Enum):
PI = 3.14
...
area = Constant.PI * r * r
I can just say:
area = PI * r * r
Is there an easy way to get from Constant.PI
to just PI
?
An enum in C# is declared by the enum keyword followed by the enumeration name and its values within a bracket. The following is an example of an enum, Day. In the above example, the first enumeratorenumeratorin computer programming, a value of an enumerated type. Enumerator (computer science), a Turing machine that lists elements of some set S. a census taker, a person performing door-to-door around census, to count the people and gather demographic data. a person employed in the counting of votes in an election.https://en.wikipedia.org › wiki › EnumeratorEnumerator - Wikipedia has the value 0, and the value of each successive enumerator is increased by 1.
The officially supported method is something like this:
globals().update(Constant.__members__)
This works because __members__
is the dict
-like object that holds the names and members of the Enum class.
I personally find that ugly enough that I usually add the following method to my Enum classes:
@classmethod
def export_to(cls, namespace):
namespace.update(cls.__members__)
and then in my top level code I can say:
Constant.export_to(globals())
Note: exporting an Enum to the global namespace only works well when the module only has one such exported Enum. If you have several it is better to have a shorter alias for the Enum itself, and use that instead of polluting the global namespace:
class Constant(Enum):
PI = ....
C = Constant
area = C.PI * r * r
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