问题描述
总之,问题是:是否有办法阻止Python查找当前范围之外的变量?详细信息:
如果Python未在当前作用域中定义,则在外部作用域中查找变量定义。因此,如果在重构过程中不小心,这样的代码很容易中断:
def line(x,a,b):
返回a + x * b
a,b = 1,1
y1 =行(1,a,b)
y2 =行(1,2, 3)
如果我重命名函数参数,但忘记在函数体中重命名它们,仍然可以运行:
def line(x,a0,b0):
return a + x * b#not一个错误
a,b = 1,1
y1 =行(1,a,b)#正确的重合结果
y2 =行(1,2,3)#错误结果
我知道从外部作用域映射名称是一种不好的做法。然而,有几个原因可以做到这一点:
- 有时可能有相同的名称,因为它们指的是同样的东西
- 一个可能用完有意义的变量名称
- laziness
有没有办法阻止Python查找当前范围之外的变量? (在第二个例子中,访问 a
或 b
会产生一个错误。)
由于懒惰,我宁愿选择一种解决方案,而不用反复使用样板代码:)
如果问题不明确Python的版本,我主要对Python 3.3及以上版本感兴趣。
不,你不能告诉Python不要看名字如果可以的话,您将无法使用在模块中定义的其他类或函数,否则不会使用 模块中定义的其他类或函数。从其他模块导入的对象,也不能使用内置名称。你的函数命名空间变成了一个没有几乎所有需要的东西的沙漠,唯一的出路就是将所有东西都导入到本地命名空间中。 您的模块中的每个函数。
与其尝试打破全局查找,保持全局名称空间不变。不要添加你不需要与模块中的其他范围共享的全局变量。例如,使用 main()
函数来封装真正的本地人。
In short, the question: Is there a way to prevent Python from looking up variables outside the current scope?
Details:
Python looks for variable definitions in outer scopes if they are not defined in the current scope. Thus, code like this is liable to break when not being careful during refactoring:
def line(x, a, b):
return a + x * b
a, b = 1, 1
y1 = line(1, a, b)
y2 = line(1, 2, 3)
If I renamed the function arguments, but forgot to rename them inside the function body, the code would still run:
def line(x, a0, b0):
return a + x * b # not an error
a, b = 1, 1
y1 = line(1, a, b) # correct result by coincidence
y2 = line(1, 2, 3) # wrong result
I know it is bad practice to shadow names from outer scopes. However, there are a few reasons why this is done anyway:
- Sometimes it may make sense to have the same names because they refer to the same thing
- One might run out of meaningful variable names
- laziness
Is there a way to prevent Python from looking up variables outside the current scope? (So that accessing a
or b
raises an Error in the second example.)
On account of being lazy, I would prefer a solution that works without repeated boiler-plate code :)
If the issue is ambiguous in terms of Python version, I'm mostly interested in Python 3.3 and above.
No, you cannot tell Python not to look names up in the global scope.
If you could, you would not be able to use any other classes or functions defined in the module, no objects imported from other modules, nor could you use built-in names. Your function namespace becomes a desert devoid of almost everything it needs, and the only way out would be to import everything into the local namespace. For every single function in your module.
Rather than try to break global lookups, keep your global namespace clean. Don't add globals that you don't need to share with other scopes in the module. Use a main()
function for example, to encapsulate what are really just locals.
Also, add unittesting. Refactoring without (even just a few) tests is always prone to create bugs otherwise.
这篇关于在Python中禁用全局变量查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!