Installing package as editable with multiple packages with same top-level module breaks import

I have the following directory structure:

.
├── client
│   └── main.py
├── lib1
│   ├── setup.py
│   └── top
│       ├── __init__.py
│       └── lib1
│           └── __init__.py
└── lib2
    ├── setup.py
    └── top
        ├── __init__.py
        └── lib2
            └── __init__.py

lib1 and lib2 are two different packages which both provides submodules inside the top module.

The client directory contains a python project using both lib1 and lib2. The contents of main.py is:

import top.lib1
import top.lib2

When installing the two libraries by path inside a virtual environment everything works:

$ python -mvenv /tmp/venv1
$ source /tmp/venv1/bin/activate
$ pip install ./lib1 ./lib2
$ python client/main.py

However if I install one of the libraries as editable, one of the imports stops working:

$ python -mvenv /tmp/venv2
$ source /tmp/venv2/bin/activate
$ pip install ./lib1 -e ./lib2
$ python client/main.py
Traceback (most recent call last):
  File "/.../client/main.py", line 1, in <module>
    import top.lib1
ModuleNotFoundError: No module named 'top.lib1'

Is there a fix for this?


I’m using Python 3.9.6 and the contents of setup.py for lib1 is (it is similar for lib2):

from setuptools import setup

setup(
    name="lib1",
    author="example",
    author_email="example@example.com",
    packages=[
        "top.lib1",
    ],
    version="0.0.1",
)

Answer

If I delete the two top/__init__.py files, then it works for me.

$ rm */top/__init__.py
$ cat > client/main.py <<EOF
import top.lib1
import top.lib2
print(top)
print(top.lib1)
print(top.lib2)
EOF
$ repro2/venv2/bin/python client/main.py 
<module 'top' (namespace)>
<module 'top.lib1' from '.../so68922155/repro2/venv2/lib/python3.9/site-packages/top/lib1/__init__.py'>
<module 'top.lib2' from '.../so68922155/lib2/top/lib2/__init__.py'>

I put the code from your question into a GitHub repository.