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

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

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"}')
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. So I'm reasonably satisfied.

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
unary, and the non-unary ** is already taken for exponentials.

So, I don't have a perfect name for my proposed quoteless synonym for
'["attrname"]'. My best option is '*.attrname'. Note that this could also be
used for unpacking, and with defaults:
d*.a #=== d["a"]
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?


(ps. I mistakenly sent this reply to python-dev earlier; sorry, this is the
right place for it. Minor edits in this version.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110325/d3aa23f5/attachment.html>

More information about the Python-ideas mailing list