Reputation: 20928
I have the following files:
./main.py
./lib/__init__.py
./lib/lib.py
,
$ cat lib/lib.py
def method():
return 'method'
,
$ cat lib/__init__.py
from .lib import *
,
$ cat main.py
import lib
def main():
print(lib.lib)
if __name__=='__main__':
main()
I don't know why lib.lib
is defined, it's not a variable in the lib.py file.
Any ideas?
Upvotes: 2
Views: 577
Reputation: 1121924
The lib.lib
object is the nested lip.py
file inside the lib
package.
Once you have imported the sub module, it also becomes available as an attribute of the package (unless you also included a lib
name in the __init__.py
file.
The Python 3.3 module loader (which is implemented in Python) simply sets a nested module as an attribute on the parent:
# [find a loader and load the module object, setting sys.modules[name]] module = sys.modules[name] if parent: # Set the module as an attribute on its parent. parent_module = sys.modules[parent] setattr(parent_module, name.rpartition('.')[2], module)
This behaviour is more or less implied in the Python packages documentation:
All modules have a name. Subpackage names are separated from their parent package name by dots, akin to Python’s standard attribute access syntax. Thus you might have a module called
sys
and a package calledemail.mime
and a module within that subpackage calledemail.mime.text
.
Upvotes: 3