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
from module import function creates package reference to the module #71730
Comments
Hello, I've found an issue in python 2.7 and 3.4 and I don't if this is a bug or a feature that acts strange to me. The import of a module or method from a module creates a reference in the package to that module only the first time, which could lead to unexpected behavior. Description:
Situation 1 is unexpected because I did not create the reference to 'module a', python did that with the statement 'from package.a import test' and this will happen from any place in the code that loads 'module a' for the first time. The documentation says that this reference will not be created. Kind regards, Marc # FILES USED # test.py def test():
print('from module a') # --------------------- def test():
print('from module b') # --------------------- #import a # <--- this line fixes the code to what I expected
import b as a
from a import test # --------------------- import package
print(dir(package))
package.a.test() |
I'm not at a computer where I can verify what you're seeing, Marc,but I should mention that at least for Python 3 your imports are wrong as you should be doing relative imports, e.g. |
The same example can be constructed for python3 by modifying the imports. I think what is happening here is that if a has not yet been imported, then when 'from .a import test' is done, the import machinery loads a and then defines 'a' in the local namespace, overriding the previous 'import package.b as a'. On the other hand, if a has already been imported, the import machinery finds 'a' in sys.modules and skips the import-and-set-name-in-local-namespace step. IMO the bug is that 'a' gets set at all when 'from a import test' is done, but the fact that it does so has a long history. |
So the problem is that you doing IOW everything is working as expected (and I still wish people weren't allowed to import objects out of modules directly). |
Note that conceptually this is closely related to bpo-27515. In both cases the conceptual problem (the thing that trips up user expectations) is that what import does to the namespaces differs depending on whether the base module exists in sys.modules or not. I don't know that there is a fix, but it is certainly an inconsistency that causes mental hiccoughs. |
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: