我最近在我们的代码中遇到了许多这样的地方
...
globals()['machine'] = otherlib.Machine()
globals()['logger'] = otherlib.getLogger()
globals()['logfile'] = datetime.datetime.now().strftim('logfiles_%Y_%m_%d.log')
Run Code Online (Sandbox Code Playgroud)
而且我对人们为什么这样做而不是做的感到有点困惑
global machine
machine = otherlib.Machine()
Run Code Online (Sandbox Code Playgroud)
等等.
这是一个稍微匿名的功能,完整地执行此操作:
def openlog(num)
log_file = '/log_dir/thisprogram.' + num
if os.path.exists(log_file):
os.rename(log_file, log_file + '.old')
try:
globals()["log"] = open(log_file, 'w')
return log
except:
print 'Unable to open ' + log_file
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
它混淆了pylint(0.25)以及我.
是否有任何理由对其进行编码?在我们的代码中使用最少的eval,这不在库中
PS我在python中检查了globals()的原因,但它并没有真正回答为什么你用这个来设置程序中的全局变量
也许该函数使用了一个与全局变量同名的局部变量,而程序员不想费心去改变变量名?
def foo(bar):
global bar # SyntaxError
bar = bar + 1
Run Code Online (Sandbox Code Playgroud)
def foo(bar):
globals()['bar'] = bar + 1
foo(1)
print(bar) # prints 2
Run Code Online (Sandbox Code Playgroud)
另一个用例,尽管仍然有点似是而非(显然不是您给出的示例函数中的情况),是动态定义变量名称。这很少是一个好主意,但至少在这个网站上确实出现了很多问题。例如:
>>> def new_variable():
... name = input("Give your new variable a name! ")
... value = input("Give your new variable a value! ")
... globals()[name] = value
...
>>> new_variable()
Give your new variable a name! foo
Give your new variable a value! bar
>>> print(foo)
bar
Run Code Online (Sandbox Code Playgroud)
否则,我只能想到这样做的一个原因:也许某些监督实体要求所有全局变量都以这种方式设置,例如“为了真正非常清楚地表明这些变量是全局的”。或者也许同一监管实体已全面禁止该global关键字,或者让程序员为每行付费。
我并不是说这些都是一个很好的理由,但话又说回来,如果不是出于范围界定的目的,我真的无法想象以这种方式定义变量的好理由(即使如此,这似乎也值得怀疑...... )。
为了以防万一,我做了一个计时检查,看看调用是否globals()比使用关键字更快。我预计函数调用+字典访问会明显变慢,事实确实如此。
>>> import timeit
>>> timeit.timeit('foo()', 'def foo():\n\tglobals()["bar"] = 1',number=10000000)
2.733132876863408
>>> timeit.timeit('foo()', 'def foo():\n\tglobal bar\n\tbar = 1',number=10000000)
1.6613818077011615
Run Code Online (Sandbox Code Playgroud)
鉴于您发布的代码和我的计时结果,我认为您正在查看的代码没有合理的理由这样编写。看起来要么是管理要求被误导,要么就是无能。