Create object name from string value?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Jan 21 21:21:58 EST 2010
On Thu, 21 Jan 2010 06:23:17 -0800, Gnarlodious wrote:
>> The right way to solve this problem is with a dictionary:
>>
>> for name in ["object1", "object2", "object3"]:
>> d = {name: classname()}
>> print d[name]
>
> This works! However I end up saying:
>
> d['Server'].Config.BaseURL
>
> to get the data, when I should be saying:
>
> Server.Config.BaseURL
There are three moments in time that the programmer needs to care about:
when you write the code, when you compile the code, and when you run the
code. In this case, the two relevant ones are write-time and run-time.
If you expect to be able to write
Server.Config.BaseURL
then that means that you MUST know the name "Server" at write-time.
(Otherwise, how do you know to write "Server", instead of "MyServer" or
"ServerSix"?) That means that the *name* Server isn't specified at
runtime, but at write-time. Since you already know the name, then the
right solution is to do something like:
Server = classname()
and then refer to Server, just like you would do:
x = 45
print x+1
or similar.
But if you are getting the name "Server" from a config file at runtime,
say something like this:
name=Server
class=classname
flag=True
then you can't write:
Server.Config.BaseURL
in your source code, because you don't know if it will be called
"Server", or "MyServer" or "Server42", or "WebServe", or "Fred". In
general, you don't even know how many servers there will be: there could
be one, or none, or fifty. So you need a level of indirection, hence the
dictionary.
--
Steven
More information about the Python-list
mailing list