Importing v reloading modules modules

Gabriel Genellina gagsl-py2 at
Sat Mar 20 02:28:12 CET 2010

En Fri, 19 Mar 2010 14:09:09 -0300, Peter Peyman Puk  
<peter_peyman_puk at> escribió:

> I am running a simulator written in python. The simulator has a small  
> TextView (actually a SourceView) widget which lets the user writes  
> scripts, and when they are satisfied they can execute that script to get  
> results. For arguments sake, we write a simple script and save it as  
> and we import it and execute it more or less like so.
> import A
> #assume there is a function called test() in module A
> A.test()
> Then the user modifies the contents of and saves it again (to  
> now all we have to do is the following
> if 'A' in dir():
>   reload(A)
> else:
>   import A
> A.test()

Terry Reedy already gave you an answer for this import problem.
I'd like to go one step back and question whether using import/modules is  
the right thing here.
Clearly is not a module but a script (that's the word you used) - and  
one does not *import* a script but *executes* it.
That is, instead of using import/__import__, use exec (or execfile) within  
a known namespace:

import __builtin__
ns = {'__builtins__': __builtin__.__dict__}
exec contents_of_textview in ns
# any change made to ns is visible here

Gabriel Genellina

More information about the Python-list mailing list