[Tutor] creating variables at runtime
Lloyd Kvam
lkvam@venix.com
Thu, 24 Jan 2002 17:11:09 -0500
I believe you are right about creating specific dictionaries to support this. I went to
the trouble of creating a list to avoid checking every __getattr__ key argument against
globals(). Using a dictionary to provide both the check and the function reference makes
a lot of sense.
Thank you very much!
Jeff Shannon wrote:
>>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
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582