name-spaces and loading a file

Justin Sheehy dworkin at ccs.neu.edu
Mon Feb 21 08:21:16 CET 2000


Alex Shinn <foof at eyeofdog.com> writes:

> Can you pickle a function (I just tried and it didn't work, but I may
> be missing something)?

Yes, you can:

>>> def testfun(a):
...     print a
... 
>>> pickle.dump(testfun, open('/tmp/p1', 'w'))
>>> test2 = pickle.load(open('/tmp/p1'))
>>> test2('spam!')
spam!

> class Scene:
>     def __init__(self, game, name):
>         "Initialize a Scene from a file"
>         # Reference the parent game
>         self.game = game
>         # Load the scene and adjust the history
>         if game.history.has_key(name):
>             exec 'reload(scenes.'+name+')'
>             game.history[name] = game.history[name] + 1
>         else:
>             scene = __import__('scenes.'+name)
>             game.history[name] = 1
>         # Translate the module variables into class variables
>         exec 'vars = dir(scenes.'+name+')'
>         for v in vars:
>             if not v[0] == '_':
>                 exec 'self.'+v+' = scenes.'+name+'.'+v

Yikes.  At the very least, you should get rid of all of that
unecessary exec'ing.  Here are some recommendations on basic cleanup,
just to get rid of the things that you definitely want to lose.

You can replace this line:

>             exec 'reload(scenes.'+name+')'

with:

reload(sys.modules['scenes.'+name])

Why are you doing this:

>             scene = __import__('scenes.'+name) 

if you never use the variable 'scene' again?

Also, this will normally return the package 'scenes', not the module
'scenes.name'.  If you wanted 'scenes.name' you should have done:

scene = __import__('scenes.'+name, globals(), locals(), [name])

Read the documentation for '__import__()'.

You can replace this section:

>         exec 'vars = dir(scenes.'+name+')' 
>         for v in vars: 
>             if not v[0] == '_': 
>                 exec 'self.'+v+' = scenes.'+name+'.'+v 

with:

scene = sys.modules['scenes.'+name]
for v in dir(scene): 
    if not v[0] == '_': 
        setattr(self, v, getattr(scene, v)) 

Note the pleasant lack of 'exec'.  

-Justin

 




More information about the Python-list mailing list