[Tutor] Importing Modules Within Classes

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Fri Oct 7 16:45:58 CEST 2005



Kent Johnson a écrit :
> Daniel Watkins wrote:
> 
>[...]
> 
>>However, someone (I don't recall who) said that there were occasions
>>when it would be appropriate to import modules the former way. I was
>>just wondering under what circumstances importing should be done this
>>way?
> 
> 
> That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all.
> 
> import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace.
> 
> So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them.
> 
> I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed.
> 
> Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil!
> 

A third reason is not to load module that will probably not be used :)
In my code, I have objects that have geometrical representations. My
objects can produce images of themselves using differente libraries.
Some are huge and takes time and memory to load ... also one specific
user will probably use only one such library at a time (and will
probably load it before ...) As each function run is quite time
consuming, adding the module check is not a problem also ! (never import
a module in a small function likely to be called in an inner-loop !)

Pierre

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68


More information about the Tutor mailing list