Why use "locals()"
Sean DiZazzo
half.italian at gmail.com
Mon Sep 14 00:54:00 EDT 2009
> > I have never used a call to "locals()" in my code. Can you show me a
> > use case where it is valuable and Pythonic?
>
> def print_item(item):
> description = textwrap.fill(item.description, 40)
> short = item.description.split('\n', 1)[0]
> code = str(item.id).zfill(6)
> print "%(code)s %(short)s\n%(description)s\n" % locals()
I see the use of that, but according to Zen, "Explicit is better than
implicit."
>
> Transferring arguments:
>
> def foo(some, long, list, of, arguments):
> additional = 5
> return other(**locals())
>
Why not?:
def foo(**kwargs):
kwargs["additional"] = 5
return other(**kwargs)
> Defining properties:
>
> class ColourThing(object):
> @apply
> def rgb():
> def fset(self, rgb):
> self.r, self.g, self.b = rgb
> def fget(self):
> return (self.r, self.g, self.b)
> return property(**locals())
>
So really it's just a short hand. But it's against the Zen! Explicit
not Implicit! I'm not convinced....then again, I didn't look at the
source code of the standard libraries.
~Sean
More information about the Python-list
mailing list