Search code examples
pythonsetuptoolspython-packaging

Python setuptools: packaging the root directory (no subdirectory per package wanted)


I need to write a package into a repository, but it is a small quick package, so I don't see the need to put files into a subdirectory. I simply want:

import mypkg.module1

with directory structure

root_folder/
    - setup.py
    - __init__.py  # the init for package "mypkg" (empty)
    - module1.py

And I don't want to be constrained to increase the folder hierarchy like here:

root_folder/
    - setup.py
    - mypkg/  # WHY would I do that for 1 module??
        - __init__.py
        - module1.py
# Content of setup.py
from setuptools import setup

setup(name='MyPkg',
      packages=['mypkg']
      package_dir={'mypkg': '.'})

but as a result, import mypkg fails, and import module1 works, instead of the desired import mypkg.module1.

I found this question, but the answer of "just move setup.py one folder up" does not suit me.

After finding setup argument documentation here, I tried to define a namespace package:

# Content of setup.py with a namespace package
from setuptools import setup

setup(name='MyPkg',
      packages=['thisdir']
      package_dir={'thisdir': '.'},
      namespace_packages=['mypkg'])

Solution

  • Without testing, I think maybe something like that could work:

    #!/usr/bin/env python3
    import setuptools
    setuptools.setup(
        name='MyPkg',
        version='0.0.0.dev0',
        packages=['mypkg'],
        package_dir={
            'mypkg': '.',
        },
    )
    

    The biggest issue is that, as far as I remember, you will end up with setup.py in the package mypkg as well, so that import mypkg.setup will indeed import the setup module. I have not verified.

    The other big issue is that, as with most of the package_dir modifications, the "develop/editable" installation will most likely not work at all.


    but as a result, import mypkg fails, and import module1 works, instead of the desired import mypkg.module1

    I could imagine this happening, if the project is not actually installed, and the current working directory is the project's root directory.

    For import mypkg to succeed you have to make sure the project is correctly installed (python -m pip install .).

    And for import module1 to fail, you might need to change to a different directory.


    Related: