#992 import code breaks loading of several modules in one binary

closed
nobody
python (259)
5
2009-03-01
2009-02-09
Gaetan Lehmann
No

Previously, it was possible to link several modules in a single binary. The modules where loaded from the main init_Module() function. This is a very useful feature for huge libraries and build systems limited to a few binary produced (msvc for exampe).

Now we can't do that in python 2.6, because of the code used to import the module in the shadow classes, which explicitly search for the module file with imp.find_module() which obviously doesn't exist in that case.

if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
try:
fp, pathname, description = imp.find_module('_itkImagePython', [dirname(__file__)])
_mod = imp.load_module('_itkImagePython', fp, pathname, description)
finally:
if fp is not None: fp.close()
return _mod
_itkImagePython = swig_import_helper()
del swig_import_helper
else:
import _itkImagePython

If I understand correctly, this code has been introduced to fix the syntax error with older python and explicit relative import. The exec statement doesn't seem to be usable, so here is how it can be implemented to preserve the ability to link several modules in one:

if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
# search for the module
fp, pathname, description = imp.find_module('_itkImagePython', [dirname(__file__)])
except ImportError:
# not found - try to simply import it, in case it is already loaded
import _itkImagePython
return _itkImagePython
if fp is not None:
# module has been found - lets load it
try:
_mod = imp.load_module('_itkImagePython', fp, pathname, description)
finally:
fp.close()
return _mod
_itkImagePython = swig_import_helper()
del swig_import_helper
else:
import _itkImagePython

Discussion

  • KL
    KL
    2009-02-23

    The current code also breaks py2exe support for SWIG on Python 2.6:

    File "mylibrary\mylibrary.pyc", line 20, in swig_import_helper:
    UnboundLocalError: local variable 'fp' referenced before assignment

    As it fails with an ImportError. The standard "import _mylibrary" works.

     
  • Haoyu Bai
    Haoyu Bai
    2009-03-01

    • status: open --> closed
     
  • Haoyu Bai
    Haoyu Bai
    2009-03-01

    Thanks, this is fixed in SVN commit 11141.