import / from ... import
In Python, the import statement loads a module. Using from ... import brings specific names directly into scope, and as assigns an alias. Standard library, third-party, and local modules all use the same syntax but are located in different places. The __name__ == "__main__" guard lets you switch behavior between running a file as a script and importing it as a module.
Syntax
# Import an entire module.
import module_name
# Import multiple modules at once.
import module_name1, module_name2
# Import a module with an alias.
import module_name as alias
# Import a specific name from a module.
from module_name import name
# Import multiple names at once.
from module_name import name1, name2
# Import a name with an alias.
from module_name import name as alias
# Import a submodule from a package.
from package_name import submodule_name
# Guard: run only when executed directly as a script.
if __name__ == "__main__":
# Code here does not run when the file is imported.
Keywords and Syntax
| Syntax | Notes |
|---|---|
| import module_name | Imports the entire module. Access names as module_name.name. |
| import module_name as alias | Assigns an alias to the module. Useful for shortening long names. |
| from module_name import name | Brings the specified name into the current namespace so you can use it without the module prefix. |
| from module_name import name as alias | Imports a name with an alias. Useful for avoiding name collisions. |
| from module_name import * | Imports all public names from the module. Tends to cause name collisions, so it is generally avoided in production code. |
| __name__ | Special variable containing the module's name. Its value is "__main__" when the file is run directly. |
| if __name__ == "__main__": | Guard block that runs only when the file is executed directly. Not executed when the file is imported. |
Sample Code
The basic usage of import and from ... import. This sample uses the standard library modules math and random. Note that the reproducibility of random.seed() may vary depending on the Python minor version.
basic_import.py
# import module_name: loads the entire module. # Access names as module_name.name. import math import random # Use functions and constants from the math module. print(math.sqrt(2)) # square root print(math.floor(2.9)) # floor function print(math.pi) # pi # Use functions from the random module. random.seed(42) # Fix the seed to make results reproducible. print(random.randint(1, 100))
python3 basic_import.py 1.4142135623730951 2 3.141592653589793 82
Using from ... import to bring specific names into scope. The module prefix can be omitted, making the code shorter.
from_import.py
# from math import name: brings only the specified name into scope.
# No module prefix needed.
from math import sqrt, pi, floor
print(sqrt(144)) # same result as math.sqrt
print(pi) # same result as math.pi
print(floor(7.8)) # same result as math.floor
# from random import: bring only the needed functions into scope.
from random import choice, seed
# Pick one pilot from Evangelion.
pilots = ["Ikari Shinji", "Ayanami Rei", "Souryuu Asuka Langley", "Nagisa Kaworu", "Makinami Mari Illustrious"]
seed(0)
selected = choice(pilots)
print("Selected pilot:", selected)
python3 from_import.py 12.0 3.141592653589793 7 Selected pilot: Nagisa Kaworu
Assigning aliases with as. Useful for shortening long module names or avoiding name collisions.
import_as.py
# import module_name as alias: assign an alias to the module.
import datetime as dt
# Access using the alias.
today = dt.date.today()
print("Today:", today)
# from ... import name as alias: alias an imported name.
from math import pi as PI, sqrt as sq
print("Pi:", PI)
print("sqrt(25) =", sq(25))
# Aliases are handy when names collide.
from random import choice as random_choice, seed as random_seed
departments = ["Operations", "Technical", "Medical", "Intelligence"]
random_seed(42)
print("Department:", random_choice(departments))
python3 import_as.py Today: (date when executed) Pi: 3.141592653589793 sqrt(25) = 5.0 Department: Intelligence
Splitting code into local modules. This sample extracts Evangelion pilot data into a separate file.
eva_pilot.py
# eva_pilot.py: local module containing pilot data.
# Place this file in the same directory as main.py.
UNIT_MAP = {
"Ikari Shinji": "Unit-01",
"Ayanami Rei": "Unit-00",
"Souryuu Asuka Langley": "Unit-02",
"Nagisa Kaworu": "Unit-13",
"Makinami Mari Illustrious": "Unit-02 Kai",
}
def get_unit(pilot_name):
"""Returns the unit name for the given pilot."""
return UNIT_MAP.get(pilot_name, "Unknown")
def list_pilots():
"""Returns a list of all pilot names."""
return list(UNIT_MAP.keys())
main.py
# main.py: imports and uses the eva_pilot module.
# import file_name (without the .py extension)
import eva_pilot
# Access via module_name.function_name.
pilots = eva_pilot.list_pilots()
for name in pilots:
unit = eva_pilot.get_unit(name)
print(name + " -> " + unit)
# You can also import just the function with from ... import.
from eva_pilot import get_unit
print(get_unit("Ayanami Rei"))
python3 main.py Ikari Shinji -> Unit-01 Ayanami Rei -> Unit-00 Souryuu Asuka Langley -> Unit-02 Nagisa Kaworu -> Unit-13 Makinami Mari Illustrious -> Unit-02 Kai Unit-00
Using the __name__ == "__main__" guard. Code inside the guard runs only when the file is executed directly, not when imported.
angel_detector.py
# angel_detector.py: angel detection module.
# Can be run standalone or imported by another file.
ANGELS = ["Sachiel", "Shamshel", "Ramiel", "Zeruel", "Armisael"]
def is_angel(name):
"""Returns True if the name is an Angel."""
return name in ANGELS
def alert(name):
"""Displays an Angel detection alert."""
if is_angel(name):
print("WARNING: Angel " + name + " detected.")
else:
print(name + " is not an Angel.")
# This block runs only when executed directly as a script.
# It is NOT executed when this file is imported.
if __name__ == "__main__":
print("--- Angel Detection System Online ---")
for target in ["Ramiel", "Nagisa Kaworu", "Zeruel"]:
alert(target)
python3 angel_detector.py --- Angel Detection System Online --- WARNING: Angel Ramiel detected. Nagisa Kaworu is not an Angel. WARNING: Angel Zeruel detected.
nerv_ops.py
# nerv_ops.py: uses angel_detector as an imported module.
# The if __name__ == "__main__" block in angel_detector.py is NOT executed.
import angel_detector
# Only the functions are available.
print(angel_detector.is_angel("Sachiel")) # True
print(angel_detector.is_angel("Ikari Shinji")) # False
angel_detector.alert("Shamshel")
python3 nerv_ops.py True False WARNING: Angel Shamshel detected.
Common Mistakes
Common Mistake 1: Circular imports causing ImportError
When module A imports module B, and module B imports module A, a circular import occurs. Python returns a partially initialized module object on the second import, causing ImportError or AttributeError when attributes are accessed.
eva_a.py
# eva_a.py: imports eva_b.
import eva_b
def get_unit_a():
return "Unit-01"
print("eva_a loaded, unit from b:", eva_b.get_unit_b())
eva_b.py
# eva_b.py: imports eva_a (circular import).
import eva_a
def get_unit_b():
return "Unit-00"
print("eva_b loaded, unit from a:", eva_a.get_unit_a())
python3 eva_a.py Traceback (most recent call last): ... AttributeError: partially initialized module 'eva_b' has no attribute 'get_unit_b' (most likely due to a circular import)
To fix this, move the import inside the function that needs it, or extract the shared dependency into a separate file to break the cycle.
Common Mistake 2: Name collision from from X import *
Using from module import * floods the current namespace with all public names from the module. When multiple modules are imported with import *, functions or variables with the same name overwrite each other, making it hard to know which is active.
ng_star_import.py
# ng_star_import.py: name collision from import * from math import * from random import * # random also has seed(), which may collide with math # It is unclear which module floor() comes from. print(floor(3.7)) print(pi)
ok_named_import.py
# ok_named_import.py: import names explicitly from math import floor, pi from random import seed, choice # It is clear which module each name comes from. print(floor(3.7)) print(pi) seed(42) pilots = ["Ikari Shinji", "Ayanami Rei", "Souryuu Asuka Langley", "Nagisa Kaworu", "Makinami Mari Illustrious"] print(choice(pilots))
python3 ok_named_import.py 3 3.141592653589793 Ikari Shinji
Common Mistake 3: Typo in module name causing ModuleNotFoundError
A spelling error in a module name or file name raises ModuleNotFoundError. Standard library module names are usually all lowercase, so mixing in uppercase letters is a common source of errors.
ng_typo_import.py
# ng_typo_import.py: spelling errors import Math # wrong: correct name is math (all lowercase) import DateTime # wrong: correct name is datetime (all lowercase)
python3 ng_typo_import.py ModuleNotFoundError: No module named 'Math'
ok_correct_import.py
# ok_correct_import.py: correct module names import math import datetime print(math.pi) print(datetime.date.today())
python3 ok_correct_import.py 3.141592653589793 (date when executed)
Notes
When Python encounters an import statement, it searches for and loads the module. Importing the same module multiple times only loads it once; subsequent imports return the cached result from sys.modules. The search order is: current directory → PYTHONPATH environment variable → standard library → third-party packages (site-packages).
Because from module import * floods the current namespace with all public names, it tends to cause name collisions and debugging difficulties and is generally avoided in production code. Defining an __all__ list in a module explicitly limits which names are exported by import *.
The __name__ == "__main__" guard is an idiom for improving module reusability. Placing test or demonstration code inside the guard prevents unintended execution when the file is imported by another script. Related features include sys.argv (command-line argument access) and os.path (path manipulation).
If you find any errors or copyright issues, please contact us.