-
Notifications
You must be signed in to change notification settings - Fork 0
stdlib
An excellent and in-depth overview provides this article.
- A *module is a
.py
file - A package is a collection of modules (usually a folder containing modules)
If in a directory Python treats those as packages. This mechanism prevents unintentional packages to be shadowed. Any subfolder/subpackage must indclude a __init__.py
file that it can be imported.
The __init__.py
file can be empty or contain initialisation code for this package.
You have the following directory structure:
└── toplevel
├── ...
├── lib
│ ├── __init__.py
│ ├── sub
│ │ ├── __init__.py
│ │ └── myScript2.py
│ ├── myLib.py
│ └── ...
├── scripts
└── ...
import lib.myLib
# lib.sub.myScript2.someFunction() # does not work since it is a subpackage
# Works when importing:
import lib.sub
lib.sub.myScript2.someFunction()
Limit what is imported when from lib import *
appears.
In __init__.py
add a list named __all__
which states the modules to be imported:
__all__ = ["sub", "..."]
Say myScript2
wants to use something in lib
you can use absolute imports:
from toplevel.lib.myLib import blah
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License *.
Code (snippets) are licensed under a MIT License *.
* Unless stated otherwise