Create object name from string value?

Dave Angel davea at ieee.org
Thu Jan 21 11:21:26 EST 2010


Gnarlodious wrote:
> 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 =lassname()")
>>     
>
> 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.
>
> -- Gnarlie
> http://Gnarlodious.com/Gnarlodious
>
>   
I know you figure you have a specific list of files, and that they'll 
never conflict with the other global variables you've defined.  But 
adding globals dynamically is "magic", and can lead to very obscure 
bugs.  Suppose sometime in the future somebody adds another plist file 
with the same name as one of your functions?

Put it inside a dummy class, as follows:

 >>> class Plist: pass
...
 >>> plists = Plist()
 >>> setattr(plists, "Server", 42)
 >>> plists.Server
42
 >>>

That avoids the ["Server"] syntax, but still doesn't risk polluting your 
global namespace with arbitrary names.  And in the example above, you'd 
be using
   plists.Server.Config.BaseURL


And if you must use the global namespace, you can simply do:

 >>> globals()["Server"] = 42
 >>> Server
42

DaveA




More information about the Python-list mailing list