'accessing a module from a package whose init file imports that module via AS keyword

Sorry for the confusing title. I tried at least! Here is my directory structure:

root\
    mypackage\
        __init__.py
        mymodule.py
    main.py

mymodule.py

print('inside mymodule.py')

__init__.py

print('inside __init__')
from . import mymodule as m

main.py

import mypackage
print(mypackage.m)
print(mypackage.mymodule)  # <--- Why does it work?

and the output:

inside __init__
inside mymodule.py
<module 'mypackage.mymodule' from 'C:\\Users...\\mypackage\\mymodule.py'>
<module 'mypackage.mymodule' from 'C:\\Users...\\mypackage\\mymodule.py'>

in main.py file, when I import mypackage, this label actually refers to the __init__.py file, so I can access all the objects/labels inside that module. It makes sense that mypackage.m works because m is now a symbol inside the __init__.py's global namespace.

But there is no mymodule key/symbol inside __init__.py's namespace because I rebind the mymodule symbol to m label via as m.

question: So why this print(mypackage.mymodule) works without throwing any exception?

Additional information : If I have another module inside the package, let's say temp.py, then print(mypackage.temp) won't work because again mypackage refers to __init__.py.
Also it's interesting for me that if I write print(mymodule) inside the __init__.py and I run the main.py module, it will run correctly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source