11

我是 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

谁能告诉我我做错了什么?

4

4 回答 4

16

恐怕除了前导下划线之外还有更多问题。

当您调用 时my_function(),它仍然不会debug在其命名空间中包含您的变量,除非您从two.py.

当然,这样做意味着你最终会得到循环依赖(one.py -> two.py -> one.py),NameError除非你重构各种东西的导入和声明位置,否则你会得到 s。

一种解决方案是创建一个简单的第三个模块,它定义这样的“常量”,可以从任何地方安全地导入,例如:

constants.py
------------
debug = True

one.py
------
from constants import debug
#...

two.py
------
from constants import debug
#...

但是,我建议只为此使用内置的日志记录模块 - 为什么不呢?它易于配置、使用更简单、可靠、灵活且可扩展。

于 2009-01-30T14:01:27.200 回答
5

以下划线开头的名称不导入

from one import *
于 2009-01-30T13:07:48.340 回答
4

您还可以使用该__debug__变量进行调试。如果解释器不是以 -O 选项启动的,则它是正确的。assert 语句也可能会有所帮助。

于 2009-01-30T13:57:06.023 回答
1

A bit more explanation: The function my_function's namespace is always in the module one. This means that when the name _debug is not found in my_function, it looks in one, not the namespace from which the function is called. Alabaster's answer provides a good solution.

于 2009-01-30T14:45:32.323 回答