[Python] Scope error when returning function from function [duplicate]

Discussão em 'Python' iniciado por Stack, Março 31, 2025.

  1. Stack

    Stack Membro Participativo

    I am having issues with using function generators in python, i.e. returning functions from a function, where some of the inputs are defined via the outer function's arguments, yielding a function with lower arity. I have used this method before in other cases without issue but I have run into an error in this case and haven't been able to understand the reason. I have the following function that produces a function:

    def func1(s: set, f: Callable) -> Callable:
    def func2(x: int) -> dict:
    while x:
    s = s - {x}
    x = f(x)
    return s
    return func2

    f2 = func1({1,2,3,4}, lambda x: x-1)


    If I try f2(3), I get the error "local variable 's' referenced before assignment" related to the s = s - {x} statement. I don't understand why s is not part of the scope since I assumed it was fixed when func1 was called to create f2.

    I was able to fix this issue by instead using this method: I combine all the arguments into one function, say func3 and use the functools.partial operation, which behaves as expected:

    from functools import partial
    def func3(x: int, s: set, f: Callable) -> dict:
    while x:
    s = s - {x}
    x = f(x)
    return s

    f2 = partial(func3, s={1,2,3,4}, f=lambda x: x-1)



    When I call f2(3) I get {4} as expected.

    My understanding is that both of these approaches should yield the same result; however, I am apparently missing something about how variable scope operates in the first case. Any insight would be greatly appreciated.

    Continue reading...

Compartilhe esta Página