[Python-ideas] [Python-Dev] Dict access with double-dot (syntactic sugar)

Jameson Quinn jameson.quinn at gmail.com
Fri Mar 25 18:47:01 CET 2011


2011/3/25 Josiah Carlson <josiah.carlson at gmail.com>

> On Fri, Mar 25, 2011 at 9:00 AM, Jameson Quinn <jameson.quinn at gmail.com>
> wrote:
> > I realized that python already has a way to access the string-based
> members
> > of a dict without using quotes:
> > def expect_a_chair(chair, **kw):
> >   print "Thanks. That chair is %s." % chair
> >   if kw:
> >     for key, val in kw.iteritems():
> >       print "I wasn't expecting the (%s) %s!" % (val, key)
> > d = json.loads('{"chair":"comfy","inquisition":"Spanish"}')
> > expect_a_chair(**d)
> > try:
> >   expect_a_chair({})
> > except TypeError:
> >   print "No chair."
> > The ** operator does this. Notice that nowhere in that python code (not
> > counting the json) do I have to put "chair" in quotes.
> > Honestly, this solves my current use case. I can use functions like
> > expect_a_chair for everything I need right now.
> > But perhaps, if there were a quote-free way to access string-based dict
> > items, it should be based on this. The problem is, this ** operator is a
> > unary operator, and the non-unary ** is already taken.
> > So, I don't have a perfect name for my proposed quoteless synonym for
> > '["..."]'. My best option is '*.'. Note that this could also be used for
> > unpacking, and with defaults:
> > d*.(x,y,z) #=== (d["x"], d["y"], d['z'])
> > e=d*.(e=None) #like 'e=d.get("e", None)'.
> > Does this sound worth-it to anyone?
>
> Gut reaction:
> Dear gods, how and why does * have a . operator, and why is there a
> function being called on it?!?
> Huh; x,y,z aren't defined in that scope, that's gotta return a
> NameError for sure.
> Or wait, is that some new way to specify a vector for multiplication?
> When did Python get a vector type and literal?
>
> If punctuation is the answer, Perl is the question. Since this is
> Python, and punctuation is decidedly not the answer, I'm going to go a
> little further than before: -sys.maxint
>
> Regards,
>  - Josiah
>

OK. As I said, I think that the existing functionality as I showed in
expect_a_chair solves my dislike for using quotes for something which
logically is an attribute name. (It would be even better if json had a way
to distinguish object-like data, with well-defined parameters, from more
free-form data, but that is out of scope here.)

Jameson

ps. A true masochist could do something like my unpacking '*.' by a
horrendous abuse of the lambda syntax:
(lambda x,y,z,e=None, **kw:oh_please_god_no(locals()))(**d)
I leave the definition of oh_please_god_no as an exercise for the reader. :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110325/fc7cd98c/attachment.html>


More information about the Python-ideas mailing list