我有一个局部变量x = "local"
,不幸的是它与全局变量和非局部变量共享它的名称。在不更改任何名称的情况下,我可以访问所有三个值吗?因为x = "global"
有globals()
,但是非局部变量呢?
说明问题的最小示例:
x = "global"
def f(x="nonlocal"):
def g():
x = "local"
print(x) # same as locals()["x"]
print(globals()["x"])
# here I want to print the non-local x
return g
f()()