Weird python sys.path module resolution behavior

63 Views Asked by At

I produced a minimal example of behavior that I thought was weird.

├── a
│   └── com
│       ├── __init__.py
│       └── x
│           ├── __init__.py
│           └── test1.py
└── b
    └── com
        ├── __init__.py
        └── x
            ├── __init__.py
            └── test2.py

In the prior filestructure I set my working directory to the one that contains 'a' and 'b'. Then I run

# Works
python3 -c "import sys; sys.path = ['a', 'b']; import com.x.test1"
# Error
python3 -c "import sys; sys.path = ['a', 'b']; import com.x.test2"

For the second example, it seems that the first sys path entry matches the common prefix, but when it ultimately can't find module test2 it errors out. I would have expected python to resolve it by matching the module prefix in the next sys path entry and finding the module in the b folder. Why doesn't it work like this? Seems like this makes it really hard for multiple packages in an organization with the same namespace to collaborate.

0

There are 0 best solutions below