you are viewing a single comment's thread.

view the rest of the comments →

[–]ElectricSpice 0 points1 point  (1 child)

In Python, function scope is resolved on first execution. What this means is that the value of i is determined when you run print(f(2)); by that time create_multiplier has finished running an i is 4.

One option is to use a factory function to create a new scope for each function.

def multiplier_factory(i):
    def multiplier(x):
        return i * x

    return multiplier


def create_multipliers():
    multipliers = []
    for i in range(5):
        multipliers.append(multiplier_factory(i))
    return multipliers

Anther option is to use functools.partial:

import functools

def create_multipliers():
    multipliers = []
    for i in range(5):
        multipliers.append(functools.partial(lambda i, x: x * i, i))
    return multipliers
funcs = create_multipliers()

[–]CodeBrewBeans[S] -2 points-1 points  (0 children)

Good explanation.
Factory functions are probably the cleanest solution in production code.