Create object name from string value?

Stephen Hansen apt.shansen at gmail.com
Thu Jan 21 11:54:43 EST 2010


On Thu, Jan 21, 2010 at 6:23 AM, Gnarlodious <gnarlodious at gmail.com> wrote:

> This works! However I end up saying:
>
> d['Server'].Config.BaseURL
>
> to get the data, when I should be saying:
>
> Server.Config.BaseURL


That's the thing: you should not actually be saying that.

d['Server'].Config.BaseURL is precisely what you should be saying.

You need to adjust your expectations to the language you are using and how
it operates. Whatever aesthetic sense in you that is objecting to using a
dictionary is something you just need to get past. If you don't like the
dictionary getitem syntax, you can always do:

>>> class AttrDict(dict):
...     def __getattr__(self, key):
...             return self[key]
...
>>> a = AttrDict()
>>> a["test"] = 1
>>> a.test
1

Is there any real reason you can't write Servers["Server"].Config.BaseURL or
Servers.Server.Config.BaseURL, or is it just an itch that's bugging you? If
its the latter, then it's better to just not scratch it and it'll go away
when you get more used to the language :)

Its not easy to do what you're asking for. People ask for it every once in
awhile. But it's just not the Pythonic way to approach the problem, and
while there are things you can do to accomplish it, they're hacks and are
not guaranteed to work consistently. Its not even a oversight in Python,
something the devs never considered: its intentionally designed to be this
way.

How come a dictionary (or class as above) isn't good enough?

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100121/41b71e8f/attachment-0001.html>


More information about the Python-list mailing list