nonlocal fails ?

Michael Torrie torriem at gmail.com
Thu Nov 14 15:17:53 EST 2019


On 11/14/19 10:57 AM, R.Wieser wrote:
>> I know of no sane way that a function could work with the scope of
>> any arbitrary caller.
> 
> The trick seems to be to emulate a "by reference" call, by using a mutable 
> object as the argument and stuff the value inside of it (IIRC a tuple with a 
> single element).

Right. You could pass in a dict as an argument. You could even pass in
the caller's locals() dictionary.  I'm not sure I recommend the latter
approach, however.

> Handle it the same as any other mistake, and throw an error ?

Sure.

I'm coming more and more around to some of the ideas of functional
programming.  Doing as you suggest, reaching back to the caller's
variables, sounds extremely messy to me.  And very fragile, hard to
test, and doesn't lend itself to easily extended functionality by
chaining(think unix-style piping).

I find Python's ability to return tuples virtually eliminates any need I
have to "pass by reference."

I'm coming around to the idea that wherever possible, functions should
have no side effects.  Those things that need side effects should be
isolated so they are easy to maintain.  I believe they call this "push
side effects to the edges."


More information about the Python-list mailing list