[Python-ideas] Dict-like object with property access

Massimo Di Pierro massimo.dipierro at gmail.com
Mon Jan 30 15:58:46 CET 2012


In web2py we have a class called Storage. (web.py has a similar class too).

works exactly like this except that if you do mydict.someprop and someprop does not exist returns None (which plays the role of JS undefined) instead of raining an exception. Users like this a lot because they can do:

    a = mydict.somevalue or 'somedefault'

which new users find more readable than

   a = mydict.get('somevalue','somedefault')

mydict.__getattr__ is the single most called method in web2py and it does affect performance. It it were supported natively by the language we would benefit from it.

Massimo


On Jan 26, 2012, at 11:47 AM, Guido van Rossum wrote:

> On Thu, Jan 26, 2012 at 9:25 AM, anatoly techtonik <techtonik at gmail.com> wrote:
>> I expected to find the answer to this question in FAQ, but because there is
>> no FAQ I ask it anyway.
>> 
>> How about adding a new standard dict-like container type that allows access
>> using . (dot) to its members instead of ['index']?
>> Why? It is convenient to write options.help instead of options['halp'] etc.
>> 
>> Example:
>>>>> mydict = container(someprop=somevalue)
>>>>> mydict['someprop']
>> somevalue
>>>>> mydict.someprop
>> somevalue
>>>>> mydict.otherprop
>> Exception KeyError ...
>> 
>> I know that it is easy to implement, but wouldn't it be nice to make it
>> available by default?
>> A side benefit of having this in stdlib is that newbies will be aware of the
>> behaviour of derived classes without having to understand the mechanics of
>> magic methods.
> 
> That is pretty much JavaScript's 'object', and I hate this ambiguity.
> If your keys are always constants, define a proper options class so
> you can say options.help instead of options['help']. You can also
> write a generic subclass of dict that works this way, if you really
> think you like it so much. But please keep it out of the stdlib. It
> leads to confused users, not happy users. An example of the problems
> that arise: If d['a'] == d.a, then how come d['clear'] != d.clear ?
> 
> -- 
> --Guido van Rossum (python.org/~guido)
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas




More information about the Python-ideas mailing list