[Tutor] creating variables at runtime
Lloyd Kvam
pythontutor@venix.com
Thu, 24 Jan 2002 08:52:54 -0500
An interesting thread.
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']()
I am enclosing a python snippet that (I think) shows why this makes sense. I have not
found this in the text books.
class Site(Table):
fk_obj_list = ['Reservation','Siteprice']
class Siteprice(Table):
class Reservation(Table):
class Table(Record,DataSet):
def __getattr__(self, key):
''' trap attempts to fetch related Table objects
'''
if key in self.fk_obj_list:
obj = globals()[key]() # <== Factory method ?????
...
# run SQL to get relevant data into obj
...
obj.Parent = self # remember where we came from
return obj
else:
return Record.__getattr__(self, key)
site = Site()
# run SQL to choose a site
reservations = site.Reservation
# reservations contains DataSet of all reservations for the site
The general approach was inspired by "Python Programming on Win32", but the
obj = globals()[key]()
must be blamed on me. It sort of seems like cheating, but has worked nicely for us.
Andy W wrote:
> Sorry for butting in and all, but I couldn't help but throw my two cents in
> :o)
> (A solution)
>
>
>>Note shell prompts:
>>
>> >>> def shell():
>> while 1:
>> i = raw_input("Name: ")
>> if not i:
>> break
>> names.append(i)
>> exec(i + " = C()")
>>
>>
>> >>> class C:
>> pass
>>
>> >>> names = []
>> >>> shell()
>>Name: A
>>Name: B
>>Name: C
>>Name:
>>
>> >>> dir()
>>['C', '__builtins__', '__doc__', '__name__', 'names', 'shell']
>>
>>A,B and C are gone -- the ones I created in the loop (the
>>C here is the original class definition).
>>
>>Because the exec(i + " = C()") statement creates new variables
>>*locally* to the shell() function -- then they get tossed.
>>
>>So that was my challenge: how do you write a raw_input loop
>>function *in the shell* that creates new variables at the
>>top level?
>>
>
>>>>def shell():
>>>>
> while 1:
> i = raw_input("Name: ")
> if not i:
> break
> globals()[i]=C()
>
>
>>>>class C:
>>>>
> pass
>
>
>>>>shell()
>>>>
> Name: a
> Name: b
> Name: c
> Name:
>
>
>>>>dir()
>>>>
> ['C', '__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'shell']
>
> Andy
>
>
>>Sorry again for not being clear.
>>
>>Kirby
>>
>>
>>
>>_______________________________________________
>>Tutor maillist - Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
> _______________________________________________
> 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