问题
I'm speaking about the general case. Here's an example:
c = 1
def a():
def b():
print(c)
b()
c = 2
a()
This code will return the following error:
NameError: free variable 'c' referenced before assignment in enclosing scope
. While the logical assumption is that the output should be 1
. What is the Pythonic solution to this issue? Use the global
or nonlocal
statements (which I don't like)? Maybe just avoid such situations, where multiple scopes share variables with identical names?
回答1:
Passing it as a parameter
When passing a outside variable as a parameter, avoid reusing names unless it's not possible that this variable can handle any other variable as parameter, then it doesn't really matter otherwise it will be confusing if you pass d
the next time and you do operations on c
within the function.
Secondly, the value of c
will not get modified within the function even if changing name from param
to c
(it has very little meaning) when passing as a variable because it's not considered as a global varaible, even tho the variable is an object it will only be a object in this function unless you pass it into a class.
c = 1
def a(param):
def b():
print(param)
b()
param = 2
a(c)
You would need to stick to the global option if you don't want to pass it as a parameter and you still want to affect c
outside of your function.
The global option will affect the "outside" c variable as your want it to.. but this is not really considered best practice, avid it if possible.
c = 1
def a():
global c
def b():
print(c)
b()
c = 2
a()
Here's what i would recommend:
c = 1
def a(param):
def b():
print(param)
b()
param = 2
return param
c = a(c)
Or even:
c = 1
def b(param):
print(param)
def a(param):
b(param)
param = 2
return param
c = a(c)
来源:https://stackoverflow.com/questions/16363387/what-is-the-pythonic-way-to-avoid-reference-before-assignment-errors-in-enclosin