user71111
user71111

Reputation: 21

Creating static function in Python using variables outside

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

Upvotes: 0

Views: 34

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96172

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)

Upvotes: 1

Related Questions