__import__ function broken in 2.6

Paul Paul22000 at gmail.com
Sat Apr 25 17:37:12 EDT 2009


Hi

It seems in 2.6 you are no longer able to use the __import__ function
with different paths. Here is our code:

		sys.path = g.origSysPath[:] # copy, not reference
		sys.path.insert(0, modulePath)

		sys.modules = g.origSysModules.copy()
		if sys.modules.get(moduleName):
			del sys.modules[moduleName]

		# look for modules in subdirectories
		moduleName = "module_"+moduleName+"/"+moduleName

		module = __import__(moduleName)

Unfortunately, this no longer works in 2.6. Does anyone have any idea
on how to make it work with file paths?

After quite a lot of searching, I was actually able to find a patch
that someone made to fix this. Here is the code:

sfepy.googlecode.com/issues/attachment?
aid=-8587746048072650671&name=import.patch

---------------------------------------------------------------------------

commit 2e92019ef957b547856e81a144db6845bf95d881
Author: Robert Cimrman <cimrman3 at ntc.zcu.cz>
Date:   Thu Mar 5 09:59:59 2009 +0100

    fixed load_classes() for Python 2.6

    - __import__() function does not work when passing a file path as
name

diff --git a/sfepy/terms/__init__.py b/sfepy/terms/__init__.py
index 3fab007..34a31a6 100644
--- a/sfepy/terms/__init__.py
+++ b/sfepy/terms/__init__.py
@@ -10,9 +10,9 @@ def load_classes( filenames, is_class ):
     table = {}
     for filename in filenames:
         name = os.path.splitext( filename )[0]
-#        print filename, name
-        mod = __import__( name )
-#        print mod
+        parts = name.split( os.path.sep )
+        mod, name = '.'.join( parts ), parts[-1:]
+        mod = __import__( mod, globals(), locals(), name )
         for key, var in mod.__dict__.iteritems():
             if is_class( key ):
                 table[var.name] = var

---------------------------------------------------------------------------

However, after a lot of messing around with the new __import__( mod,
globals(), locals(), name ) function, I am still unable to make it
work. Perhaps I am just not able to understand exactly what is going
on here.

Can anyone offer some assistance?

Thank you,
Paul



More information about the Python-list mailing list