New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Behaviour of modules depends on how they where imported #65752
Comments
I found a condition where different behaviour could be observed depending on how a module is imported. It seems to be different to write: import module
# against:
from package import module In the attachment you find a minimal package (imptest) with this organization: imptest And two scripts which can be directly executed: Contents of the module m: Contents of module subm: Both run0.py and run1.py imports module m and calls the do() function, thus theoretically changing foo to 1. I found that this actually depends on how I imported m in the script. Contents of run0.py: Result: As you can see from printout "importing subm", the m module is imported again and thus foo is reset to 0. In run1.py, Contents of run1.py: Result: I know that directly running a module in the first level of a package may seem strange or not correct, but could someone explain why this is happening? |
Here's a simpler demo for what I believe you are experiencing: $ mkdir package
$ cd package/
$ touch __ini__.py module.py
$ export PYTHONPATH=..
$ python3
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import module, package.module
>>> module is package.module
False Even though module and package.module correspond to the same file A good way to avoid this trap is to use relative imports >>> from . import module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: Parent module '' not loaded, cannot perform relative import |
This is a consequence of a script's directory getting prepended to sys.path. See issue bpo-13475. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: