Writing import module_name runs that module's code once, the first time it's imported in a given program, since subsequent imports reuse the already-loaded, cached module instead of re-running it, and binds the module itself as an object to a name in the current scope. Everything inside the module — functions, classes, variables — is then accessed through attribute access on that name, keeping the importing code's own namespace uncluttered by everything the module defines.
1Understanding import Statement
Writing import module_name runs that module's code once, the first time it's imported in a given program, since subsequent imports reuse the already-loaded, cached module instead of re-running it, and binds the module itself as an object to a name in the current scope. Everything inside the module — functions, classes, variables — is then accessed through attribute access on that name, keeping the importing code's own namespace uncluttered by everything the module defines.
Python caches every imported module after its first import — this is why import statements are cheap to repeat across many files, and why top-level module code, like print statements or expensive setup, only actually runs once per program, no matter how many places import it.
import math
print(math.sqrt(16))
print(math.pi)2Practical Example
Here is a real-world application of import Statement showing how it is used in production Python code.
import random
random.seed(42)
print(random.randint(1, 100))3Best Practices
Follow these guidelines when working with import Statement:
1. Use import module and access things through the module name for clarity about where a name comes from, unless a specific name is used extremely often
2. Put all imports at the top of a file, grouped by standard library, third-party, and local imports, per PEP 8
3. Avoid import *, which pulls an unpredictable set of names into your namespace and makes it unclear where any given name actually came from
Tip: Python caches every imported module after its first import — this is why import statements are cheap to repeat across many files, and why top-level module code, like print statements or expensive setup, only actually runs once per program, no matter how many places import it.
import math
print(math.sqrt(16))
print(math.pi)