Derivative of string as a name of list or dictionary (or class?)
John Hunter
jdhunter at nitace.bsd.uchicago.edu
Fri Jul 26 12:15:24 EDT 2002
>>>>> "Roman" == Roman Tarantowicz <rtaranto at interia.pl> writes:
Roman> I received string1, string2, ... etc from handle_data in
Roman> MyParser(SGMLParser)
Roman> I dont know how to create list or dictionary which name be
Roman> derivative of the received string?
Roman> I would like to have the following containers:
Roman> Top_Category = [derivative_of_string1,
Roman> derivative_of_string2, ...]
Roman> Derivative _of_string1 = [derivative_of_another_string1,
Roman> derivative_of_another_string2, ...]
Roman> Derivative_of_another_string1 = {'id1': 'str1', 'id2' :
Roman> 'str2', ...}
Roman> Is this any direct method or I have to apply something
Roman> complicated as a Factory Pattern (is it possible to
Roman> automate producing new classes which names will be given
Roman> during execution of program)? Any tips or direction in
Roman> which my mind should be pushed I'll embrace wholeheartedly
Roman> ;)
If you want to set attributes of a class you can use setattr and name
the attributes with a string, as in
class SomeClass:
pass
name = 'seq'
val = ['John', 'Hunter', 'was', 'here']
x = SomeClass()
setattr(x, name, val)
print x.seq
#or
print getattr(x,name)
If you want to set variable names in the global namespace, I am
reasonably sure you can do a similar thing by manipulating a global
object, but I don't know what it is. You can always use exec, but you
will probably have people frown at you
name = 'seq'
val = ['John', 'Hunter', 'was', 'here']
exec('%s=val' % name)
print seq
But I would hold out to see if a better solution exists.
John Hunter
More information about the Python-list
mailing list