Suppose I have the following function that returns a function:
def make_square_matrix_creator(dim):
mat = np.zeros([dim, dim])
def square_matrix_creator(value):
mat += value
return mat
return square_matrix_creator
Now, this code doesn't work, because the internal function can't access mat
.
f = make_square_matrix_creator(4)
f(3)
UnboundLocalError: local variable 'mat' referenced before assignment
I know there are a few ways to get around this; I can make mat
global:
def make_square_matrix_creator(dim):
global mat
mat = np.zeros([dim, dim])
def square_matrix_creator(value):
global mat
mat += value
return mat
return square_matrix_creator
It works, but this has all of the problems associated with making global objects within functions
I can pass mat as a default argument to the internal function;
def make_square_matrix_creator(dim):
mat = np.zeros([dim, dim])
def square_matrix_creator(value, mat=mat):
mat += value
return mat
return square_matrix_creator
But when I try this out in my real-world example, I run into problems with mutable defaults. Are there other options for giving an internal function access to objects created in its parent function?