[Tutor] creating variables at runtime
Jeff Shannon
jeff@ccvcorp.com
Thu, 24 Jan 2002 11:01:01 -0800
> Lloyd Kvam <pythontutor@venix.com> wrote:
>
> I've been using globals() in kind of the reverse way to create class instances based
> on the desired class name, sort of a quick Class Factory Method.
> instance = globals()['Classname']()
Actually, this is much closer to the "right" way to use globals(), I think. I know that
the corresponding locals() function returns a dictionary that should be considered
read-only (effects of altering it are undefined), and my gut reaction is to try to treat
globals() the same way (though, admittedly, I don't see a similar warning about globas()
in the docs). Then again, in almost any case where something like this might be useful,
I'd prefer to create a dictionary and just use that. For instance, in your sample code...
> class Site(Table):
> fk_obj_list = ['Reservation','Siteprice']
> class Siteprice(Table):
> class Reservation(Table):
I'd do this as:
class Siteprice(Table):
class Reservation(Table):
class Site(Table):
fk_objects = { 'Reservation': Reservation, 'Siteprice': Siteprice }
and then when I needed to create the class, I could do
if key in self.fk_objects.keys():
obj = self.fk_objects[key]()
Of course, this may just be my personal style, and YMMV and all, but I think that this is
more explicit, and cleaner, than using globals().
Jeff Shannon
Technician/Programmer
Credit International