mwlon
mwlon

Reputation: 1006

How to import two submodules in python with the same subfolder name

My project structure looks like this:

project/
  main.py
  sub_a/
    class_a.py
    __init__.py
    utils/
      __init__.py
      util_a.py
  sub_b/
    class_b.py
    __init__.py
    utils/
      __init__.py
      util_b.py

And in each of class_a.py, class_b.py, there is an import like this:

from utils import util_a/b

My PYTHONPATH points to both sub_a and sub_b. When I try to

import class_b

in main.py, I get an ImportError:

ImportError: cannot import name util_b

I am using Python 2.7.

I understand that the error comes about because from utils import util_b is ambiguous, so Python chooses the first one on the path, but how can I rewrite the imports so that they work?

I don't think changing the PYTHONPATH is an option, since each of sub_a and sub_b assume they are part of the PYTHONPATH in their own internal imports. For instance, the from utils import util_b in class_b.py.

Upvotes: 0

Views: 390

Answers (2)

ivan_pozdeev
ivan_pozdeev

Reputation: 35986

Don't add both subdirectories to PYTHONPATH. Instead, add only project to it and import sub_a.utils.util_a and sub_b.utils.utils_b.
(In the packages themselves, you can use relative imports to import things from the same subtree. E.g. in sub_b/__init__.py: import .utils.utils_b)

As per isinstance fails for a type imported via package and from the same module directly , if you add the subdirectories, utils package gets associated with whichever is earlier on sys.path and only it will be searched whenever you try to import anything from utils.

Upvotes: 1

Alex R
Alex R

Reputation: 77

What you looking for is 'Import As'

Good overview here: Answered in another thread from ... import OR import ... as for modules'

from project.sub_a import User as aUser

from project.sub_b import User as bUser

Upvotes: 0

Related Questions