Create object name from string value?

Alf P. Steinbach alfps at start.no
Thu Jan 21 09:43:05 EST 2010


* Gnarlodious:
> On Jan 20, 10:35 pm, Steven D'Aprano wrote:
> 
>> That's the wrong way to handle the problem. Named objects are only useful
>> if you know the name of the object when writing the code. Otherwise, how
>> do you know what name to use in the code?
> 
> Thank you for the help. I am gathering the names of all *.plist files
> in a folder, creating objects named the filename, and accessing the
> data like this:
> 
> Data.Server.Config.BaseURL
>> http://Spectrumology.com/
> 
> Adding a .plist file would automatically create a plist dictionary
> object inside the Data module.
> 
>> 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
> 
>> but for the record, the way to use exec is like this:
>>
>> exec("object1 = classname()")
> 
> I failed to make that work. So back to the original question. How to
> make an instance named according to a string inside a variable? I
> guess it should be in the top-level namespace, not inside a list or
> dictionary.

I don't understand how you intend to use a variable whose name comes from 
dynamic data.

So I agree with Steven that it's the wrong way to handle the problem  -- 
whatever the problem is!

But, if it can help:


   >>> import __main__
   >>> setattr( __main__, "blah", 123 )
   >>> blah
   123
   >>> _


Cheers,

- Alf



More information about the Python-list mailing list