我可以使用 __init__.py 来定义全局变量吗? [英] Can I use __init__.py to define global variables?

查看:31
本文介绍了我可以使用 __init__.py 来定义全局变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个常量,它应该在一个包的所有子模块中都可用.我认为最好的位置是在根包的 __init__.py 文件中.但我不知道如何做到这一点.假设我有几个子包,每个子包都有几个模块.如何从这些模块访问该变量?

当然,如果这是完全错误的,并且有更好的选择,我想知道.

解决方案

您应该能够将它们放在 __init__.py 中.这一直是这样做的.

mypackage/__init__.py:

MY_CONSTANT = 42

mypackage/mymodule.py:

 from mypackage import MY_CONSTANT打印我的常量是",MY_CONSTANT

然后,导入 mymodule:

<预><代码>>>>从 mypackage 导入 mymodule我的常数是 42

不过,如果你确实有常量,将它们放在一个单独的模块(constants.py、config.py、...)中是合理的(可能是最佳实践),然后如果你想要它们在包中命名空间,导入它们.

mypackage/__init__.py:

from mypackage.constants import *

不过,这不会自动包含包模块的命名空间中的常量.包中的每个模块仍然必须从 mypackage 或从 mypackage.constants 显式导入常量.

I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the __init__.py file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules?

Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.

解决方案

You should be able to put them in __init__.py. This is done all the time.

mypackage/__init__.py:

MY_CONSTANT = 42

mypackage/mymodule.py:

from mypackage import MY_CONSTANT
print "my constant is", MY_CONSTANT

Then, import mymodule:

>>> from mypackage import mymodule
my constant is 42

Still, if you do have constants, it would be reasonable (best practices, probably) to put them in a separate module (constants.py, config.py, ...) and then if you want them in the package namespace, import them.

mypackage/__init__.py:

from mypackage.constants import *

Still, this doesn't automatically include the constants in the namespaces of the package modules. Each of the modules in the package will still have to import constants explicitly either from mypackage or from mypackage.constants.

这篇关于我可以使用 __init__.py 来定义全局变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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