[New-bugs-announce] [issue46806] Overlapping PYTHONPATH may cause

aklajnert report at bugs.python.org
Sun Feb 20 07:34:47 EST 2022


New submission from aklajnert <python at aklajnert.pl>:

I'm not 100% sure whether it is a bug or intentional behavior but looks like a bug to me. I couldn't find anything about it here or anywhere else.

Sample project structure:
```
.
├── main.py
└── src
    ├── __init__.py
    ├── common_object.py
    ├── user_1.py
    ├── user_2.py
    └── user_3.py
```

`__init__.py` is an empty file.


```
# src/common_object.py
OBJECT = object()
```

```
# src/user_1.py
from .common_object import OBJECT
```

```
# src/user_2.py
from src.common_object import OBJECT
```

```
# src/user_3.py
from common_object import OBJECT
```

```
# main.py
import sys

sys.path.append("src")

from src import user_1, user_2, user_3


if __name__ == '__main__':
    print(user_1.OBJECT is user_2.OBJECT) # True
    print(user_1.OBJECT is user_3.OBJECT) # False
```

Since `src` package is added to `PYTHONPATH`, it is possible to import `common_object` by calling `from src.common_object` or `from common_object`.  
Both methods work, but using import without `src.` makes Python load the same module again instead of using the already loaded one.

If you extend `main.py` with the following code, you'll see a bit more:
```
modules = [
    module
    for name, module in sys.modules.items()
    if "common_object" in name
]
print(len(modules)) # 2
print(modules[0].__file__ == modules[1].__file__) # True
```

In the `sys.modules` dict there will be two separate modules - one called `common_object` and another named `src.common_object`. 
If you compare the `__file__` value for both modules you'll see that they are the same. It seems that python gets the module name wrong.

----------
messages: 413584
nosy: aklajnert
priority: normal
severity: normal
status: open
title: Overlapping PYTHONPATH may cause
type: behavior
versions: Python 3.10, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46806>
_______________________________________


More information about the New-bugs-announce mailing list