bleh
bleh

Reputation: 101

Python package name conflict

I have (ended up with) my packages being setup in the following way. There are two packages with the same name, but one of them is inside package_a.

    ├── package_a/
    │   ├── __init__.py
    │   └── package_aa/
    │       ├── __init__.py
    │       └── module_a.py
    │   └── module_c.py
    └── package_aa/
        ├── __init__.py
        └── module_b.py

How do I import both module_a.py and module_b.py in my code? The following

from package_a.package_aa import module_a; from package_aa import module_b;

fails with the error message

ImportError: cannot import name 'module_b' from 'package_aa' (.\package_a\package_aa\__init__.py)

All __init__.py files contain a single line

import os, sys; sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))

Renaming is unfortunately not an option as I am not the owner of these packages.


EDIT : Swapping works. Thanks. I have a follow up question : Suppose in module_c.py, modula_a.py is imported like this from package_aa import module_a. Then the following fail with similar error, but it is not as apparent (to the user) as in the original question

from package_aa import module_b; from package_a import module_c

How can the owner of package_a modify it so that its users don't run into errors like this? I am starting to think, the way __init__.py is written might not be right. Although, I have seen answers elsewhere which suggests adding sys.path.append or sys.path.insert in this fashion.

Upvotes: 0

Views: 769

Answers (1)

Maxime Bonnesoeur
Maxime Bonnesoeur

Reputation: 76

My guess would be to swap them like this:

from package_aa import module_b
from package_a.package_aa import module_a

This way, package_aa is not referenced in the path.

Upvotes: 1

Related Questions