3

I have several Python packages that I'd like to keep on separate filesystems but which unfortunately share the same top-level module name.

To illustrate, the directory structure looks like this:

/fs1
  /top
    __init__.py
    /sub1
      __init__.py

/fs2
  /top
    __init__.py
    /sub2
      __init__.py

In Python 2.7, is there any way I can set up my PYTHONPATH so that I could import both top.sub1 and top.sub2 into the same script? Adding both /fs1 and /fs2 doesn't work, since it only allows one of the two submodules to be imported (whichever comes first on PYTHONPATH).

I could copy/symlink the two trees into one, but for practical reasons I'd rather not do that.

1
  • 2
    Yes, there is a way, and it's called "namespace packages". stackoverflow.com/questions/1675734/… Note that if you do this, the top package has to be empty, that namespace can not contain anything except the sub1 and sub2 packages. Commented Jul 20, 2013 at 6:15

1 Answer 1

1

There are several options, one of which is imp:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

(my source)


Another is with importlib

Relative:

importlib.import_module('.sub1', 'fs1.top')

Absolute:

importlib.import_module('fs1.top.sub1')

(my source)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.