Deferred imports

Tom Plunket gamedev at fancy.org
Fri Jul 14 19:10:56 EDT 2006


I'm using this package that I can't import on startup, instead needing
to wait until some initialization takes place so I can set other
things up so that I can subsequently import the package and have the
"startup needs" of that package met.

Specifically this has to do with the interaction between wxPython and
Pygame.  (see http://wiki.wxpython.org/index.cgi/IntegratingPyGame,
toward the bottom, after the "On Windows however..." heading for my
writeup about the problem.)

So as y'all might guess, I have the solution in this sort of thing:

import os
global myDeferredModule

class MyClass:
   def __init__(self):
      os.environ['MY_DEFERRED_MODULE_PARAM'] = str(self)
      global myDeferredModule
      import myDeferredModule

m = MyClass()

HOWEVER, my problem now comes from the fact that other modules need to
use this import.  So, I need to either use the above "trick", or I
need to just import the module in every function that needs it (which
will be almost exclusively the constructors for the objects as they're
the ones creating Pygame objects).

So my question is, is 'import' heavy enough to want to avoid doing it
every time an object is created, or is it fairly light if it's
currently active somewhere else in the application?  I suppose that
may depend on how many objects I'm creating, and how frequently I'm
creating them, but if 'import' resolves to essentially 

if not global_imports.has_key(module):
   do_stuff_to_import_module

...then I'm not so worried about putting it into every constructor.
Otherwise I'll do this trick, starting myDeferredModule = None and
only do the import if not None.

Thanks!

-tom!



More information about the Python-list mailing list