jmhummel
jmhummel

Reputation: 109

Move python modules to subdirectory without breaking imports

Original project foo:

/foo
    /module_a
        /module_aa
    /module_b
    ...

Where in the original project, module_b contains imports such as import module_a

In the new project, bar I'd like to have:

/bar
    app.py
    /foo
        /module_a
            /module_aa
        /module_b
    ...

However, this breaks the imports in the foo subdirectory:

    File "/bar/foo/module_b"
        import module_a
ModuleNotFoundError: No module named 'module_a'

What should I do here, to avoid having to update/modify all of the import statements in the foo directory?

Upvotes: 0

Views: 354

Answers (2)

jmhummel
jmhummel

Reputation: 109

This is the cleanest I was able to get it working without modifying any of the original codebase:

/foo/__init__.py

import sys

sys.path.append("../foo")

from module_a import some_function_a
from module_b import some_other_function_b

sys.path.remove("../foo")

app.py

import foo

foo.somefunction_a()
foo.some_other_function_b()

Upvotes: 0

chepner
chepner

Reputation: 531355

This is what relative imports are for. Change

import module_a

to

import .module_a

so that module_b will look in its own package for module_a, rather than in a directory on the Python search path that no longer contains module_a.

Upvotes: 1

Related Questions