4 ms·
this made me wonder - I know I can use global variables inside a function definition: a = 1 def foo(): x = a foo() so if this 'a' is a new v
by ashtonbaker 4y ago
this made me wonder - I know I can use global variables inside a function definition:
a = 1
def foo():
x = a
foo()
so if this 'a' is a new variable, what happens when the name collides with a global variable?
a = 1
def foo():
a = a
foo()
> UnboundLocalError: local variable 'a' referenced before assignment
yuck!
- all2 4y agoI'm not sure this is so much of a problem? Changing what you name the variable fixes the issue. Python is generally quite good at having a verbose option to express things, so I'm surprised there's not an explicit way to reference the enclosing scope from an object.
- vegai_ 4y agoIs there any non-horror piece of code where supporting this latter case would be useful?
- m55au 4y agoIt is not a particularly good example. A better one would be a = 1 def foo(): x = a a = 2 foo() > UnboundLocalError: local variable 'a' referenced before assignment Basically a name cannot be both global and local inside the same function. Otherwise it would be a total mess. "a = a" just means assign the value of local variable "a" to a local variable "a", so the error makes sense.
- gilch 4y agoIt works if you disambiguate your namespaces: >>> a = 1 >>> def foo(): ... a = globals()['a'] ... print(a) ... >>> foo() 1 Still yuck?
- gilch 4y agoHere's another way to do it: >>> def foo(): ... import __main__ ... a = __main__.a ... print(a) ... >>> foo() 1