[Tutor] import and reload in modules

Garry Willgoose Garry.Willgoose at newcastle.edu.au
Mon Nov 5 04:17:01 CET 2007


In response to Kent's suggestion here is an updated post showing the  
python code and the error log. The original reason for using try was  
I thought maybe this was scoping problem and that maybe 2nd time  
through the call it needed to import it again from scratch. As a side  
observation for Kent I also tried replacing the exec on the import  
statement with __init__('siberia900') and other variants using a text  
variable and while they appeared to work I got a the following error

 >>> __import__('siberia900')
<module 'siberia900' from 'siberia900.pyc'>
 >>> siberia900.version
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'siberia900' is not defined

Maybe its related don't know.


Anyway here's the original problem again with more info.

---------------------------------
current_model_name=''

def load():
   global current_model_name
   model='siberia900'
   text1='import '+model
   text2='reload('+model+')'
   if model==current_model_name:
     print 'here 1', text2
     exec(text2)
   else:
     print 'here 10', text1
     exec(text1)
   current_model_name=model
   version=eval(model+'.version')
   return(version)
---------------------------------
 >>> import mytest1
 >>> mytest1.load()
here 10 import siberia900
'1.00'
 >>> mytest1.load()
here 1 reload(siberia900)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "mytest1.py", line 10, in load
     exec(text2)
   File "<string>", line 1, in <module>
NameError: name 'siberia900' is not defined
---------------------------------


====================================================================
Prof Garry Willgoose,
Australian Professorial Fellow in Environmental Engineering,
Director, Centre for Climate Impact Management (C2IM),
School of Engineering, The University of Newcastle,
Callaghan, 2308
Australia.

Phone: (International) +61 2 4921 6050 (Tues-Thurs); +61 2 6545 9574  
(Fri-Mon)
FAX: (International) +61 2 4921 6991 (Uni);
Env. Engg. Secretary: (International) +61 2 4921 6042
Centre WWW  :  www.c3im.org.au

email:  garry.willgoose at newcastle.edu.au
email-for-life: garry.willgoose at alum.mit.edu
====================================================================
"Do not go where the path may lead, go instead where there is no path  
and leave a trail"
                           Ralph Waldo Emerson
====================================================================






More information about the Tutor mailing list