leoschet
leoschet

Reputation: 1866

Importing modules with same name

Basically, I have two python projects, one is located under myapp/screening and the other myapp/server. I'm currently developing the server module and want to import functions from screening using myapp.screening.

My folder structure is as shown bellow:

myapp/
    screening/
        screening-env/
        myapp/
            __init__.py
            screening/
                __init__.py
                screening_task.py
                submodule1/
                    # __init__.py and ub module files
                submodule2/
                    # __init__.py and sub module files
                submodule3/
                    # __init__.py and sub module files
        tests/
            # __init__.py and test scripts
        setup.py
    server/
        server-env/
        myapp/
            __init__.py
            server/
                __init__.py
                server_task.py
        tests/
            __init__.py
            server_test.py

I structured my project following this answer.

My setup.py is basically as bellow:

from setuptools import setup

setup(
    name='myapp-screening',
    version='0.1.0',
    packages=[
        'myapp.screening',
        'myapp.screening.submodule1',
        'myapp.screening.submodule2',
        'myapp.screening.submodule3'
    ],
)

I activated my server-env and installed the screening project by navigating to myapp/screening/ (same directory as setup.py) and ran python setup.py develop.

Finally, both server_test.py and server_task are such as bellow:

from myapp.screening.screening_test import foo

foo()

When I run python -m myapp.server.server_task or python -m test.server_test I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'myapp.screening'

This error makes sense if I'm running python -m myapp.server.server_task because local myapp existis and might be overwriting the installed myapp that contains the screening modules.

Is there a way to import stuff from screening using from myapp.screening.screening_task import foo?!

Upvotes: 1

Views: 1301

Answers (1)

leoschet
leoschet

Reputation: 1866

So, after some more research I found this similar (in a way) question that leads to import python modules with the same name and How do I create a namespace package in Python?.

The answer for "importing modules with same name" is not useful since it says to rename one module or turn the project directory into a package.

The other question is exactly what I want. It basically talks about the pkgutil with which you can 'append' modules to a given namespace.

I understand and share some opinions against this technique for some cases (such as this) but since it's presented here sometimes you want separated structures so you don't patch everything togheter even when you don't want everything

Upvotes: 1

Related Questions