0

Say we have some package with several subpackages. But there's one subpackage X that is completely somewhere else in the file tree. Can we still import X as if it were subpackage? (i.e. such that X can refer to the top-level package using relative imports)

chtenb
  • 14,924
  • 14
  • 78
  • 116
  • 1
    relative imports only work within packages. packages are defined by their directory structure. So, if subpackage X isn't inside of the directory of package Y, then subpackage X isn't really a subpackage... – mgilson Dec 07 '13 at 20:46

1 Answers1

0

Assuming you do have the __init__.py file inside the directory, you could go the easy route and add the packages path to the sys path ie:

import sys
sys.path.append(path/to/package)

import module

The problem with this is it will only work if the file system stays consistent. Another way that seems to work well regardless of directory structure is answered here: Import a module from a relative path

Edit

I realize I didn't understand your question as it was asked. A subpackage X is not really a subpackage if it is not inside of the Y package, so as far as I know you can not import it as a subpackage

Community
  • 1
  • 1
samrap
  • 5,595
  • 5
  • 31
  • 56
  • This way you don't import it as a subpackage: check `print(__name__)` will just return the current name, and not all the parent packages. – chtenb Dec 07 '13 at 20:45