Dictionary self lookup

Norberto Lopes shelika.void at gmail.com
Wed Jun 24 12:21:48 CEST 2009


On Jun 24, 11:59 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Norberto Lopes wrote:
> > Hi all.
> > Assuming that python dictionaries already provide a bit of "shoot
> > yourself in the foot", I think what I have in mind would not be so
> > bad.
>
> What kind of foot-shooting do you have in mind?
>

a = { "foo" : { "bar" : "moo" }}
a["bar"] = a["foo"]
print a
{'foo': {'bar': 'moo'}, 'bar': {'bar': 'moo'}}
a["foo"]["bar"] = a["foo"]
print a
{'foo': {'bar': {...}}, 'bar': {'bar': {...}}}

(I know it's not a C shoot in the foot or something but still...)
>
>
>
>
>
>
> > 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"]
>
> > Maybe I'm murdering python syntax/philosophy right here so let me know
> > if that's the case.
> > I was thinking this could probably be done in python abstract tree but
> > as I never looked into it I may be wrong. I'm willing to make the
> > effort, provided I get some directions and that this idea is worth it.
>
> > Any feedback is welcome.
>
> Obviously the proposed syntax can't work, as at the time of the dictionary
> construction the name the dict is bound to is either not known
With just more thatn syntactic sugar this could be done

>, or even bound to *another* dict.
>
doh! Didn't thought about that one. Nice catch.

> Additionally, the code would be by no means more efficient than the
> above "long" version, as whatever notation you chose, it won't help to deal
> with the fact that the dict-object itself, and also a potentially reference
> key, aren't already available.
>
> So behind the curtain, the exact same logic would apply, with all
> runtime-costs.
>
> Which leaves us with the question: why the heck do you want this?
>
Syntactic sugar basically. I'm not ranting about performance, just
easier write up.

config = {"home" : "/home/test", "user1": config["home"] + "/user1",
"user2" : config["home"] + "/user2", "python-dev" : config["user1"] +
"/Projects/py-dev" }

config = {"home" : "/home/test"}
config["user1"] = config["home"] + "/user1"
config["user2"] = config["home"] + "/user2"
config["python-dev"] = config["user1"] + "/py-dev"


Now, if you change config["home"] you'd have to redo all of the other
entries. With the first one (assuming pointers to the entries)
everything would get updated. Although python does not handles dict
keys/values this way. Now that I think of this there would be a lot
more than just syntactic sugar for this.

(ignore the path concatenation without os.path)





More information about the Python-list mailing list