Dictionary self lookup

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jun 27 01:18:32 EDT 2009


En Wed, 24 Jun 2009 23:42:03 -0300, Carl Banks <pavlovevidence at gmail.com>  
escribió:
> On Jun 24, 2:39 am, Norberto Lopes <shelika.v... at gmail.com> wrote:

>> What do you think of dictionaries having a self lookup in their
>> declaration?
>>
>> Be able to do this:
>>
>> a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax
>>
>> instead of:
>>
>> a = { "foo" : "foo1" }
>> a["bar"] = a["foo"]
>
> If you don't mind abusing Python syntax, you can do it using something
> like this:
>
>
> def DictMaker(name,bases,dct):
>     dct.pop('__metaclass__',None)
>     return dct
>
>
> class a:
>     __metaclass__ = DictMaker
>
>     home = "/home/test"
>     user1 = home + "/user1"
>     user2 = home + "/user2"
>     python_dev = user1 + "/py-dev"

Certainly an abuse of syntax, but it's a nice trick!

-- 
Gabriel Genellina




More information about the Python-list mailing list