[Python-ideas] Jump to function as an an alternative to call function

Chris Angelico rosuav at gmail.com
Thu Aug 16 15:37:32 EDT 2018


On Fri, Aug 17, 2018 at 5:32 AM, Chris Barker via Python-ideas
<python-ideas at python.org> wrote:
> hmm -- made me think that generators are doing something different here --
> and indeed they are. If you use regular functions:
>
> In [30]: def local_modifying(loc):
>     ...:     """
>     ...:     adds a "fred" key to the dict passed in
>     ...:     """
>     ...:     print("locals passed in:", loc)
>     ...:     loc['fred'] = 5
>     ...:     print("locals after adding", loc)
>     ...:
>
> In [31]: def test_locals():
>     ...:     """
>     ...:     a simple local namespace to use
>     ...:     """
>     ...:     a = 1
>     ...:     b = 2
>     ...:     local_modifying(locals())
>     ...:     # does "fred" exist?
>     ...:     print(locals())
>     ...:     # and we can access it the usual way
>     ...:     print("fred:", fred)
>     ...:
> In [32]: test_locals()
> locals passed in: {'b': 2, 'a': 1}
> locals after adding {'b': 2, 'a': 1, 'fred': 5}
> {'b': 2, 'a': 1, 'fred': 5}
> fred: 5
>
> It seems you CAN modify the locals dict passed in, and the change will show
> up in the enclosing scope.
>
> But it sounds like that is not guaranteed by the language.

I've no idea what interpreter you're using, but it doesn't work for me.

>>> test_locals()
locals passed in: {'a': 1, 'b': 2}
locals after adding {'a': 1, 'b': 2, 'fred': 5}
{'a': 1, 'b': 2, 'fred': 5}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in test_locals
NameError: name 'fred' is not defined

You've changed a cached dictionary but haven't actually created a local.

ChrisA


More information about the Python-ideas mailing list