Questions about `locals` builtin
Kirill Balunov
kirillbalunov at gmail.com
Tue Feb 27 09:43:20 EST 2018
2018-02-27 14:59 GMT+03:00 Ned Batchelder <ned at nedbatchelder.com>:
> 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."
>
Ok, but I in this case what is the benefit in Python 3.3+ in returning a
copy of dict instead of MappingProxy?
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.
>
>
The example from "Is there are good DRY fix for this painful design
pattern?" https://mail.python.org/pipermail/python-list/2018-
February/731218.html
class Foo:
def __init__(self, bashful, doc, dopey, grumpy,
happy, sleepy, sneezy):
self.bashful = bashful # etc
def spam(self, bashful=None, doc=None, dopey=None,
grumpy=None, happy=None, sleepy=None,
sneezy=None):
if bashful is None:
bashful = self.bashful
if doc is None:
doc = self.doc
if dopey is None:
dopey = self.dopey
if grumpy is None:
grumpy = self.grumpy
if happy is None:
happy = self.happy
if sleepy is None:
sleepy = self.sleepy
if sneezy is None:
sneezy = self.sneezy
# now do the real work...
def eggs(self, bashful=None, # etc...
):
if bashful is None:
bashful = self.bashful
# and so on
and with the possibility to update `locals` the `spam` can be rewritten
with:
def spam(self, bashful=None, doc=None, dopey=None,
grumpy=None, happy=None, sleepy=None,
sneezy=None):
loc = locals()
for key, val in loc.items():
if val is None:
loc[key] = getattr(self, key)
In fact, I do not have a strict opinion on this matter. And I'd rather be
glad that PŠ½thon was less dynamic in some moments in favor of some
optimizations.
With kind regards,
-gdg
More information about the Python-list
mailing list