如何让一个Enum的成员进入全局命名空间? [英] How does one get an Enum's members into the global namespace?

查看:129
本文介绍了如何让一个Enum的成员进入全局命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python现在有一个枚举类型(在3.4中新增了使用PEP 435 ,并且 backported ),而命名空间是一件好事,有时Enums更像常数,并且枚举成员应该生活在全局(呃,模块)命名空间中。



所以而不是:

 常量(枚举):
PI = 3.14

...

area = Constant.PI * r * r

我可以说:

  area = PI * r * r 

有一个简单的方法从 Constant.PI PI

解决方案

正式支持的方法是这样的:

  globals()。update 。$ member $)

这是因为 __成员__ dict 类对象,其中包含Enum类的名称和成员。



我个人觉得丑陋我通常将以下方法添加到我的枚举类中:

  @classmethod 
def export_to(cls,namespace):
namespace.update(cls .__ members__)

然后在我的顶级代码我可以说:

  Constant.export_to(globals())

注意:将枚举导出到全局命名空间只有在模块只有一个这样的导出的枚举时才有效。如果你有几个,那么对于枚举本身来说,最好使用一个较短的别名,并使用它,而不是污染全局命名空间:

  class Constant(Enum):
PI = ....
C =常量

区域= C.PI * r * r


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?

解决方案

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

这篇关于如何让一个Enum的成员进入全局命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆