Best practices with import?

Jay O'Connor joconnor at cybermesa.com
Tue Jul 31 09:10:47 EDT 2001


Gordon McMillan wrote:
> 
> Peter Hansen wrote:
> 
> [snip]
> 
> > There is at least one situation where import in a function is very
> > useful, and that is to delay execution of the import.  If the first
> > module is imported by another, and all of its import statements are
> > at the top, each import executes at that time, slowing down loading
> > of the first module.  If one of the imported modules is needed only
> > in one of the functions, which may or may not be called, putting
> > the import statement in the function will postpone (perhaps avoid)
> > the import and improve responsiveness.

> As above, this is a sensible solution only if the use of the imported
> module is confined to the one function.


This is starting to look really attractive to me as I've got one program
that does some heavy weight processing and imports a lot of modules. 
However, for UI/User Response reasons, a long startup time is not
acceptable.  The user will be initiating some long running processes, so
doing some import prior to those processes starting is starting to look
like a good idea after reading this thread.

What's the scope of an import done in this manner?  Say I were to have a
class that imported a module in it "__init__" method; would that module
be available throughout the class?  Or the module the class is in?

class MyEngine:
	def __init__ (self):
		import engine_support

	def doSomething (self):
		#is engine_support is scope?
		engine_support.do_something()

eng = MyEngine()
eng.doSomething()

#is engine_support in scope
engine_support.do_something_else()

hmmmm...I just tested it, both  references to engine_support outside of
__init__ fail with a NameError.  *THAT* would be something useful to
have...a class level import; import the module in __init__, it's in
scope for the whole class

The best workaround for now I could think of is either to assign an
instance variable to the module


class MyEngine:
	def __init__ (self):
		import engine_support
		self._es = engine_support

	def doSomething(self):
		self._es.do_something()

That works...I tested it...

or to assign it to a global in the module so that once it's imported,
it's available to the whole module.

I can see the use for being able to import a module into a function, but
having it in visible outside of that function (especially in classes)

-- 
Jay O'Connor
joconnor at cybermesa.com
http://www.cybermesa.com/~joconnor



More information about the Python-list mailing list