Should 3.4 enums use UPPER_CASE_WITH_UNDERSCORES?

筅森魡賤 提交于 2020-08-21 07:03:10

问题


As the documentation says, an enumeration is a set of symbolic names (members) bound to unique, constant values. The PEP8 says that constants are usually named as UPPER_CASE, should I use this notation in Python 3.4 enums? If yes, why the examples in the docs are using lower_case?


回答1:


Update

The BDFL (Benevolent Dictator For Life) has spoken, and the Enum documentation has changed to reflect all upper-case member names.


The examples in the [previous] docs are lower-case primarily because one of the preexisting modules that Enum was based on used lower-case (or at least its author did ;).

My usage of enum has usually been something along the lines of:

class SomeEnum(Enum):
    ... = 1
    ... = 2
    ... = 3
globals().update(SomeEnum.__members__)

which effectively puts all the members in the module namespace.

So I would say whichever style feels more comfortable to you -- but pick a style and be consistent.




回答2:


I think they're not UPPER_CASE because, well, it just looks weird when it is. Since you can only access the enumerations through the class (e.g. my_enum.VALUE) it looks weird if the members are capitalized. In C the members of the enumeration go into the module namespace, so it doesn't look weird (to me) when the members are capitalized, in usage:

typedef enum {OFF, ON} lightswitch;
lightswitch bathroomLight = ON;

But in Python you access them through the enumeration class that you create, and it looks weird to go from ClassStyle names to ALL_CAPS.

class Lightswitch(Enum):
    OFF = 0
    ON = 1

# isn't that weird?
my_light = Lightswitch.OFF

Bottom line, I think it's just aesthetic. I've been wrong before, though, and I realize that this is just my opinion.




回答3:


When in doubt about style, I usually defer to the style used in standard library code and examples from the official documentation. It keeps me from wasting time on arbitrary decisions.

So in this case, I recommend lower case, like variable names.



来源:https://stackoverflow.com/questions/21359130/should-3-4-enums-use-upper-case-with-underscores

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!