[Python-ideas] Jump to function as an an alternative to call function
Steven D'Aprano
steve at pearwood.info
Thu Aug 16 14:51:19 EDT 2018
On Thu, Aug 16, 2018 at 09:34:57AM -0700, Chris Barker wrote:
> On Thu, Aug 16, 2018 at 1:28 AM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>
> > there
> > are times where I have really wanted to access the caller's environment,
> > not the environment where my function was defined.
> >
>
> what am I missing? can't you get that by passing locals() in to a function?
I want to pull in the caller's environment, not require the caller to
push their environment in to me.
Most of the time I just want read-access to the environment, but if I
need to modify it, and the OP needs to do that, modifying locals() is
unreliable. In general, it just silently fails, because locals()
returns a copy of the local namespace.
def spam(d):
d['a'] = 'spam'
def eggs():
a = 'ham'
spam(locals())
print(a)
Running that under CPython prints "ham", not "spam".
(To be precise, writing to locals() works when you are in the module
scope, or a class body, but not a function body. That's a CPython
implementation detail; IronPython and Jython may behave differently.)
--
Steve
More information about the Python-ideas
mailing list