[Python-ideas] Dict-like object with property access
Terry Reedy
tjreedy at udel.edu
Thu Jan 26 22:28:06 CET 2012
On 1/26/2012 12:38 PM, Mike Meyer wrote:
> On Thu, 26 Jan 2012 19:25:40 +0200
> anatoly techtonik<techtonik at gmail.com> wrote:
>> How about adding a new standard dict-like container type that allows
>> access using . (dot) to its members instead of ['index']?
We already have them: any subclass of *object*.
>>> class Option: pass
>>> options = Option
>>> options.help = 'be happy'
>>> options.help
'be happy'
Or did you mean 'instead of' to mean 'in addition to'?
That is actually possible too.
>>> options.__dict__['help']
'be happy'
>>> options_d = options.__dict__ # dict view of options
>>> options.bye = 'Nice to know you!'
>>> options_d['bye']
'Nice to know you!'
>> Why? It is convenient to write options.help instead of
>> options['halp'] etc.
>
> Because it doesn't work in general. There are strings that can be used
> as an index, but not as an attribute. There are existing attributes
> that you have to avoid, etc.
>
> The only way this really works in practice is if you start with a
> fixed set of names you want to access, in which case
> collections.namedtuple will probably do the job.
An advantage of collections.namedtuple is that all the pre-existing
attributes start with '_' so as to avoid name clashes. Another is that
name subscripts do *not* work, so there is no ambiguity there either.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list