0

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()
asked May 9, 2020 at 19:27
2
  • repeat_three = repeat_n doesn't create a new function. It's the same function Commented May 9, 2020 at 19:30
  • Even if it did copy the function, it wouldn't replace n with the value of n at the time of the copy. n is a free variable, whose value is looked up when you call the function. Commented May 9, 2020 at 20:03

1 Answer 1

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

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()

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.