all Python 3Modules & importsterm
Package and __init__.py
packages
A package is a directory of modules imported as pkg.mod. An __init__.py file makes the directory a regular package and runs on the package's first import.
Syntax
pkg/
__init__.py
mod.py
import pkg.mod
from pkg import mod
from .mod import name # внутри пакета
__init__.py runs once — on the first import pkg or import pkg.mod — and everything it defines becomes an attribute of pkg; this is how a package lifts handy names to the top: from .prices import total. A submodule does not become an attribute of the package by itself: after import pkg, pkg.mod raises AttributeError until pkg.mod is imported explicitly or from __init__.py. A directory without __init__.py imports too — as a namespace package (PEP 420, Python 3.3) whose __file__ is None; it exists for packages split across several directories and easily hides a typo in a path. A file named like a stdlib module in the script's directory (random.py, json.py) shadows the real module, because that directory comes first in sys.path.
Examples
import os, sys
sys.path.insert(0, '.')
os.makedirs('shop', exist_ok=True)
with open('shop/__init__.py', 'w', encoding='utf-8') as f:
f.write("print('выполняется shop/__init__.py')\nfrom .prices import total\n")
with open('shop/prices.py', 'w', encoding='utf-8') as f:
f.write('def total(xs): return sum(xs)\n')
import shop # → выполняется shop/__init__.py
import shop.prices # пакет уже загружен: __init__.py второй раз не выполняется
print(shop.total([1, 2, 3])) # → 6
import os, sys
sys.path.insert(0, '.')
os.makedirs('notes', exist_ok=True) # каталог без __init__.py
import notes
print(notes.__file__) # → None — пакет пространства имён
import sys
sys.path.insert(0, '.') # так стоит каталог запущенного скрипта
with open('random.py', 'w', encoding='utf-8') as f:
f.write("print('это мой random.py')\n")
import random # → это мой random.py
print(hasattr(random, 'randint')) # → False — настоящий random затенён
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy