[Tutor] Importing Modules Within Classes

Kent Johnson kent37 at tds.net
Fri Oct 7 04:21:21 CEST 2005


Daniel Watkins wrote:
> Recently, there has been an example of someone importing modules within
> a class definition. eg:
> 
> class Exemplar:
> 	import re
> 	...use re...
> 
> It seems obvious to me that this is incorrect, though more through
> training than actual observation on my part, and it should be:
> 
> import re
> 
> class Exemplar:
> 	...use re...

It's not really incorrect, it is legal syntax and it will do what you expect. It is not idiomatic and in general it is simpler to just put all the imports at the top.
 
> 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!

Kent
> 
> Cheers,
> Dan
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



More information about the Tutor mailing list