Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #29532

Re: Using dict as object

From Oscar Benjamin <oscar.j.benjamin@gmail.com>
Subject Re: Using dict as object
Date 2012-09-19 23:04 +0000
References <345da32c-a22b-4025-bb50-794d684885b1@googlegroups.com> <5059B062.8020108@davea.name> <CAJ+soVegTjd_O-UYx8t400CFxXgd2B=ngt9JNzWJUVq+YNvXJA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.945.1348095884.27098.python-list@python.org> (permalink)

Show all headers | View raw


On 2012-09-19, Pierre Tardy <tardyp@gmail.com> wrote:
> --===============1362296571==
> Content-Type: multipart/alternative; boundary=bcaec554d3229e814204ca105e50
>
> --bcaec554d3229e814204ca105e50
> Content-Type: text/plain; charset=ISO-8859-1
>
>>
>>  This has been proposed and discussed and even implemented many
>> times on this list and others.
>>
> I can find this question on SO
> http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
> which is basically answered with this solution
>
> class AttributeDict(dict):
>     __getattr__ = dict.__getitem__
>     __setattr__ = dict.__setitem__
>
>
> but this does not allow recursive access, you would need to first convert
> all nested dictionaries to AttributeDict.
> a.b.c.d = 2 # fail
> a.b = dict(c=3)
> a.b.c=4 # fail

There is no way to control "recursive access" in Python. The statement

a.b.c = 2

is equivalent to the statements

o = a.b   # o = a.__getattr__('b')
o.c = 2   # o.__setattr__('c', 2)

The way that the o.c assignment is handled is determined by the type of o
regardless of the type of a. If you're looking for a way to change only the
type of a and make a custom __(set|get)attr__ work for all dicts that are
indirectly referred to then there is no solution to your problem.

Oscar

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Using dict as object Pierre Tardy <tardyp@gmail.com> - 2012-09-19 03:24 -0700
  Re: Using dict as object Dave Angel <d@davea.name> - 2012-09-19 07:45 -0400
  Re: Using dict as object Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2012-09-19 15:02 +0200
  Re: Using dict as object Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2012-09-19 14:04 +0000
  Re: Using dict as object Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2012-09-19 23:04 +0000

csiph-web