Welcome, guest | Sign In | My Account | Store | Cart

this is a hack to get the "foo" module that's outside a package whithin a file of the package, when it also contains a module named "foo" (ie relative imports)

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import os
import sys

def pythonImport(name):
    current_path = os.path.dirname(os.path.abspath(__file__))
    base_name = os.path.basename(current_path).split('.')[0]
    sys.path[:] = [path for path in sys.path
                   if os.path.abspath(path) != os.path.abspath(current_path)]

    original_module = sys.modules[name]
    del sys.modules[name]
    python_module = __import__(name)
    python_module_name = 'python_%s' % name
    sys.modules[python_module_name] = python_module
    sys.path.append(current_path)
    sys.modules[name] = original_module
    return python_module_name, python_module

until the relatives import are delivered in Python, (http://www.python.org/peps/pep-0328.html#rationale-for-relative-imports), here's a small hack i use when I need to access a Python module in a package that contains a module with the same name.

Suppose you have this package:

package | |-- imaplib.py |-- module.py |-- __init__.py

and suppose you need to use python imaplib module in module.py. if you do a "import imaplib" it'll catch the local one.

this small function removes the current path from the paths to grab the module.

module.py:

import imaplib print dir(imaplib) # local one

module_name, module = pythonImport('imaplib') # python's one print dir(module)

1 comment

Antti Kaihola 16 years, 1 month ago  # | flag

What is "base_name" for?

"abspath(current_path)" is unnecessary in the list comprehension. "current_path" works just as well since the path is already absolute.

Is it possible that the current path is not in sys.path? If not, it's simpler to just say "sys.path.remove(current_path)".

Or, alternatively, why modify sys.path back and forth and not just copy it aside, assign a new one and get back the saved one?