Hacker News new | ask | show | jobs
by sophacles 4018 days ago
Functions can be defined in a nested way setting up closures. It isn't that different from what you wrote to do:

    def some_method(...):
        avar = aval
        .... (some code)
        def throwaway(x, y):
            ....
            something_else(avar, x+y)
        some_obj.somefunc = throwaway
The major difference is you do the function definition just prior to the assignment. The "namespace pollution" is literally limited to the scope of "some_method", so you have an extra local var in a function somewhere. The semantics of python mean that the function is created on the stack, and a closure is created each time the some_method is called, and the closure is later GCed as any other object would be, so there is nothing fundamentally different about the "named" function, and the "anonymous" function in you example, except a single local variable.
1 comments

That's what I meant. Defining the throwaway function directly before the assignment is a good compromise at least.