I need to create a set of similar static functions in python. This involves variables outside the function that I want to use as hard-coded values when a function is created. However, functions created this way remain linked to variables and change dynamically:
def repeat_n():
res = []
for _ in range(n):
res.append(1)
return res
n = 3
repeat_three = repeat_n
repeat_three()
n =+ 1
# repeats four times
repeat_three()
1 Answer 1
Assignment never creates a copy in Python, so repeat_three = repeat_n
doesn't create a new function, it merely assigns the same function object to another variable.
It looks like you just want a function factory:
def repeat_factory(n):
def repeat():
res = []
for _ in range(n):
res.append(1)
return res
return repeat
repeat_3 = repeat_factory(3)
repeat_4 = repeat_factory(4)
answered May 9, 2020 at 19:33
1 Comment
user71111
thank you! this works indeed
n = 3 def repeat_factory(n): def repeat(): res = [] for _ in range(n): res.append(1) return res return repeat repeat_3 = repeat_factory(n) n+=1 repeat_3()
lang-py
repeat_three = repeat_n
doesn't create a new function. It's the same functionn
with the value ofn
at the time of the copy.n
is a free variable, whose value is looked up when you call the function.