all Python 3Modules & importsconstruct
import / from … import
import
Loads a module: import m binds the name m, from m import x binds x, and as renames. A leading dot (from . import x) imports relative to the current package.
Syntax
import module [as name]
from module import name [as alias], …
from module import *
from . import sibling
from ..pkg import name
A module runs once, on the first import, and is cached in sys.modules: importing it again does not reread the file, so edits made while the program runs are not seen. from m import x copies the reference at import time: if m.x is later rebound, your x keeps the old value. from m import * takes the names listed in __all__, or, without it, every name not starting with an underscore. In a circular import the second module gets the first one half-executed, and from a import x fails with ImportError "partially initialized module". Relative imports work only inside a package: in a file run directly (python file.py) they fail — run it as python -m package.module instead.
Examples
import math
from math import pi
math.pi = 3 # переприсвоили имя в модуле
print(math.pi) # → 3
print(pi) # → 3.141592653589793 — у нас осталась старая ссылка
import sys
sys.path.insert(0, '.') # искать модули и в текущем каталоге
with open('greet.py', 'w', encoding='utf-8') as f:
f.write("print('модуль выполняется')\n__all__ = ['hello']\ndef hello(): return 'hi'\ndef _hidden(): pass\n")
import greet # → модуль выполняется
import greet # повторно не выполняется: модуль уже в sys.modules
print('greet' in sys.modules) # → True
from greet import *
print(hello()) # → hi
print('_hidden' in dir()) # → False
# файл запущен напрямую, а не как часть пакета
from . import helper # → ImportError: attempted relative import with no known parent package
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy