python中全局变量的困惑
我是Python新手,所以请原谅这可能是一个非常愚蠢的问题。
基本上,我有一个名为 _debug 的全局变量,用于确定脚本是否应输出调试信息。 我的问题是,我无法在与使用它的脚本不同的 python 脚本中设置它。
我有两个脚本:
one.py:
-------
def my_function():
if _debug:
print "debugging!"
two.py:
-------
from one import *
_debug = False
my_function()
运行two.py 会生成错误:
NameError: global name '_debug' is not defined
任何人都可以告诉我我做错了什么吗?
I'm new to python, so please excuse what is probably a pretty dumb question.
Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.
I have two scripts:
one.py:
-------
def my_function():
if _debug:
print "debugging!"
two.py:
-------
from one import *
_debug = False
my_function()
Running two.py generates an error:
NameError: global name '_debug' is not defined
Can anyone tell me what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
恐怕还有更多的问题不仅仅是前导下划线。
当您调用
my_function()
时,它的命名空间中仍然不会包含您的debug
变量,除非您从two.py
导入它。当然,这样做意味着您最终会遇到循环依赖关系(
one.py -> Two.py -> one.py
),并且您会得到NameError
code>s 除非您重构导入和声明各种内容的位置。一种解决方案是创建一个简单的第三个模块,它定义这样的“常量”,可以从任何地方安全地导入它,例如:
但是,我建议仅使用内置的 logging 模块 - 为什么不呢? 它易于配置、使用更简单、可靠、灵活且可扩展。
There are more problems than just the leading underscore I'm afraid.
When you call
my_function()
, it still won't have yourdebug
variable in its namespace, unless you import it fromtwo.py
.Of course, doing that means you'll end up with cyclic dependencies (
one.py -> two.py -> one.py
), and you'll getNameError
s unless you refactor where various things are imported and declared.One solution would be to create a simple third module which defines 'constants' like this, which can be safely imported from anywhere, e.g.:
However, I would recommend just using the built in logging module for this - why not? It's easy to configure, simpler to use, reliable, flexible and extensible.
以下划线开头的名称不会导入
Names beginning with an underscore aren't imported with
您还可以使用 __debug__ 变量进行调试。 如果解释器不是使用 -O 选项启动的,则确实如此。 断言语句也可能有帮助。
You can also use the
__debug__
variable for debugging. It is true if the interpreter wasn't started with the -O option. The assert statement might be helpful, too.更多解释:函数
my_function
的命名空间始终位于模块one
中。 这意味着,当在my_function
中找不到名称_debug
时,它会在one
中查找,而不是在调用该函数的命名空间中查找。 Alabaster的回答提供了一个很好的解决方案。A bit more explanation: The function
my_function
's namespace is always in the moduleone
. This means that when the name_debug
is not found inmy_function
, it looks inone
, not the namespace from which the function is called. Alabaster's answer provides a good solution.