Python - Packages
Packages:
- add structure to the module namespace
- module names from one package won’t be in conflict with the modules from another package
init.py
- dir is treated as a package if it has this file
- can be blank
- can contain init code
Example layout:
tools/ package - top level
__init__.py init package
data/ subpackage
__init__.py init
analytics.py module
crud.py module
web/ subpackage
__init__.py init
scrape.py module
capture.py module
filter.py module
Import submodules:
import tools.data.crud
Import so that we can specify the submodule directly:
from tools.data import crud
Import the function directly:
from tools.data.crud import search
tools.data.crud.search(term)
crud.search(term)
search(term)
- when using “from” you can import functions, variables, and classes
Importing * From a Package
from tools.web import * # import tools.web and run init code ( needs __all__ to import submodules )
all which submodules to import when using wildcard
all = [“scrape”, “capture”, “filter”]
__all__ = [
"scrape",
"capture",
"filter",
]
More:
import tools.web.scrape
import tools.web.capture
from tools.web import *
Intra-package References
“you can use absolute imports to refer to submodules of siblings packages”
This module:
tools.web.scrape
Can run:
tools.data import crud
Can also use relative imports:
from . import scrape
from .. import data
from ..data import crud
- Relative imports are relative to the module so they won’t work if the module name is main.
- If a module can be run as a script it needs to use absolute imports.
path also exists and can be used to change where subpackages and modules are searched for