On Fri, Nov 15, 2019 at 7:19 AM Michael Torrie <torr...@gmail.com> wrote: > > 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.
The locals() dict isn't guaranteed to be mutable. At the moment, there are very very few actual language guarantees regarding changes to locals(), but there's currently a WIP to define things a little more tightly: https://www.python.org/dev/peps/pep-0558/ Neither in the current wording nor in the proposed wording is any sort of promise that you could pass locals() to another function and have it usefully modify that. > 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." Agreed. Or Python's ability to return strings. Most of the pass-by-reference that I do in languages like SourcePawn is just to get around the problem that strings aren't first-class values. > 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." Something like that. Ideally, a function should be pure - having no side effects, being unaffected by external state, and having a return value determined entirely by its arguments. Not every function can be pure, of course (for instance, print() is most certainly NOT a pure function), but the more of your functions that are pure, and the purer your other functions are, the easier it is to reason about your code and refactor things. ChrisA -- https://mail.python.org/mailman/listinfo/python-list