Search code examples
pythonpipsetuptoolssetup.pydistutils

Python setup.py: import packages from subdirectories not specifying top level directory


I am trying to write setup.py such that I will be able to import submodules from package_3 directly, without specifying top level (from package_3 import submodule_1), not as from package_3.package_3 import submodule_1, simultaneously being able to import any submodules from package_2 and package_1 as from package_1 import submodule_1 and from package_2 import submodule_1

Directory tree:

├── package_3
│   └── package_3
│       └── __init__.py
│       └── submodule_1
|       |   └── __init__.py
|       └── submodule_2
|           └── __init__.py
├── package_2
│   └── __init__.py
|   └── submodule_1
|   |   └── __init__.py
|   └── submodule_2
|       └── __init__.py
├── package_1
│   └── __init__.py
|   └── submodule_1
|   |   └── __init__.py
|   └── submodule_2
|       └── __init__.py
├── setup.py

Could you tell me please if it is possible to achieve this using some specific configuration of setup.py without changes in directory tree (the only thing I can change is add or remove init.py)?

What I tried:

import setuptools
setuptools.setup(
  packages=setuptools.find_packages(
    include=["package_1", "package_2"]
  ) + setuptools.find_packages(include=['package_3'], where='./package_3')
 )

and then pip install -e .

Another configuration I tried:

import setuptools
setuptools.setup(
  packages=["package_1", "package_2", "package_3"],
  package_dir={
   'package_1': '.',
   'package_2': '.',
   'package_3': './package_3/package_3'
  } 
)

and then pip install -e .

Thank you for any input.


Solution

  • You could add an __init__.py of your "root-level" package_3 module to make it transparent, you could do something like :

    from .package_3 import submodule_1
    

    The requested from package_3 import submodule_1 should then work as requested.