[Python-Dev] dict() enhancement idea?

Just van Rossum just@letterror.com
Thu, 21 Nov 2002 16:16:29 +0100

Oren Tirosh wrote:

> I assume that the motive is to get rid of the quotes around the key and
> conceptually treat it as a "symbol" rather than as a string.  If that is 
> the case it could apply to access as well as initialization.
> class record(dict):
>     def __init__(self, __initfrom=(), **kw):
>         self.__dict__ = self
>         dict.__init__(self, __initfrom)
>         self.update(kw)
>     def __repr__(self):
>         return "%s(%s)" % (self.__class__.__name__,
>           ', '.join(['%s=%s' % (k, repr(v)) for k,v in self.items()]))
> Fields can be accessed as either items or attributes of a record object.

(Neat! Would've never guessed that works... I actually wrote a class with this
purpose the other day, I'll see whether I can use the above instead.)

But: no, I simply find the {"key": "value"} syntax sometimes inappropriate.
Consider the following example:

   template = """some elaborate template using %(name)s-style
   # idiom 1
   x = template % {"name1": foo(), "name2": baz()}

   # idiom 2
   name1 = foo()
   name2 = foo()
   x = template % locals()
   # idiom 3 (after my patch, or with a homegrown function)
   x = template % dict(key1=foo(), key2=baz())
I find #3 more readable than #1. #2 ain't so bad, but I hate it that when you're
quickly going over the code it looks like there are some unused variables.