Questions about `locals` builtin

Chris Angelico rosuav at gmail.com
Wed Feb 28 02:04:11 EST 2018


On Wed, Feb 28, 2018 at 5:54 PM, dieter <dieter at handshake.de> wrote:
> Ned Batchelder <ned at nedbatchelder.com> writes:
>> On 2/27/18 3:52 AM, Kirill Balunov wrote:
>>> a.  Is this restriction for locals desirable in the implementation of
>>> CPython in Python 3?
>>> b.  Or is it the result of temporary fixes for Python 2?
>>
>> My understanding is that the behavior of locals() is determined mostly
>> by what is convenient for the implementors, so that they can keep
>> regular code running as quickly as possible.  The answer to the
>> question, "why can't we make locals() work more like I expect?" is,
>> "because that would make things slower."
>>>
>>> Personally, I find the convenient functionality to update the local symbol
>>> table inside a function, similar to `globals`.
>>
>> Can you show us an example of why you would want to update locals
>> through locals()?  There might be more natural ways to solve your
>> problem.
>
> I am still working with Python 2 (Python 3 may behave differently).
> There, during debugging, I would sometimes like to change the value
> of variables (I know that the variable has got a wrong value
> and would like to fix it to continue senseful debugging without a restart).
> This works for variables not yet known inside the function but does
> not work for true local variables.
> I assume that this is one effect of the "locals()" restriction.
>

That seems like a hairy thing to do, honestly. But if you know that
there's only a handful of variables that you'd actually want to do
that to, you can simply put those into an object of some form, and
then mutate that object. That's guaranteed to work in any Python.

Personally, I'd be inclined to break things up into separate
functions, and then if you want to change state and continue, it would
be by interactively calling one of those functions with slightly
different parameters.

ChrisA



More information about the Python-list mailing list