Reputation: 60
I get UnboundLocalError: local variable 'weights' referenced before assignment
How can I get the nested function to be defined based on the weights variable?
def create_defender(weights=None):
def defender(position_1, position_2):
if not weights:
weights = [ 1, 1.25, 1.5]
...
return something
return defender
Upvotes: 0
Views: 29
Reputation: 2723
https://www.learnpython.org/en/Closures
Firstly, a Nested Function is a function defined inside another function. It's very important to note that the nested functions can access the variables of the enclosing scope. However, at least in python, they are only readonly. However, one can use the "nonlocal" keyword explicitly with these variables in order to modify them.
e.g:
def defender(position_1, position_2):
nonlocal weights
if not weights:
weights = [ 1, 1.25, 1.5]
should do what you're looking for.
Upvotes: 1