Dictionary self lookup

Jure Erznožnik jure.erznoznik at gmail.com
Sat Jun 27 07:33:25 EDT 2009


While certainly useful, this kind of functionality contradicts the way
today's "string" libraries work.
What you are proposing isn't dict self referencing, but rather strings
referencing other external data (in this case other strings from the
same dict).

When you write code like
config = {"home" : "/home/test"}
config["user1"] = config["home"] + "/user1"

config["user1"] isn't stored in memory as config["home"] + "/user1",
but as a concatenated string ("/home/test/user1"), composed of both
those strings. The reference to original composing strings is lost at
the moment the expression itself is evaluated to be inserted into the
There's no compiler / interpreter that would do this any other way. At
least not that I know of.

So best suggestion would be to simply do an object that would parse
strings before returning them. In the string itself, you can have
special blocks that tell your parser that they are references to other
objects. You can take good old DOS syntax for that: "%variable%" or
something more elaborate if "%" is used in your strings too much.

Anyway, your code would then look like (one possible way):
config = {"home" : "/home/test"}
config["user1"] = "%config["home"]%" + "/user1"


config = {"home" : "/home/test", "user1" : "%config[\"home\"]%/user1"}

The parser would then just match "%(something)%" and replace it with
actual value found in referenced variable. Eval() can help you there.
Maybe there's already something in Python's libraries that matches
your need.

But you sure better not expect this to be included in language syntax.
It's a pretty special case.


More information about the Python-list mailing list