Search code examples
pythonnamespacessetuptoolssoftware-distribution

Setuptools Subpackages with clean Namespace


I'm using setuptools 40.8.0 under python 3.7.2 to package together some modules and packages in order to make them available system-wide. My goal is to have a clean namespace, where functions are bundled together in functional units.

My folder structure looks like this:

mymodule
|  setup.py
|  mymodule
 -  | __init__.py
  - |package_foo
     - __init__.py
     - some_script.py

setup.py:

from setuptools import setup, find_packages

setup(name='mymodule',
      version='1.0',
      packages=find_packages(),
      zip_safe=False)

top level __init__.py:

from . import package_foo

second level __init__.py:

from .some_script import some_function

(I am actually not sure, why the first dot is needed in the imports but I don't seem to make it workable without.)

Now, if I do

import mymodule

I have mymodule.package_foo.some_function in my namespace (which I want), but also mymodule.package_foo.some_script (which I don't want). I could add a line in the second level __init__.py deleting some_script by doing

del some_script

but that doesn't feel right. Is there another, more elegant way to achieve what I'm trying? Or is it good practice to leave some_script in the namespace?


Solution

  • I found a workaround that works for me. If the module name starts with an underscore, it's not included in the namespace automatically. I changed some_script.py to _some_script.py and the import statements as well.