Introduction
One of Python’s strengths is its modular structure. Instead of writing everything in a single file, you can split your code into reusable modules and import only what you need. This article covers how to use Python’s import
statement effectively, including working with standard modules and creating your own.
What Are Python Modules?
A module is simply a Python file containing functions, classes, or variables. You can import a module into another Python file to reuse code.
# my_module.py
def greet(name):
return f"Hello, {name}!"
# main.py
import my_module
print(my_module.greet("Alice"))
Using the import Statement
You can import entire modules or specific elements:
import math
print(math.sqrt(25))
from math import pi
print(pi)
For large modules, importing only what you need helps reduce namespace clutter.
Aliasing with as
Use aliases to make modules easier to refer to:
import numpy as np
print(np.array([1, 2, 3]))
Built-in Modules
Python comes with a wide set of built-in modules. Here are some commonly used ones:
math
: mathematical functionsdatetime
: date and time handlingos
: operating system interfacesys
: Python runtime info
Creating Your Own Module
To create your own module, just save a Python file and import it. For example:
# utils.py
def add(a, b):
return a + b
# main.py
from utils import add
print(add(2, 3))
Conclusion
Modules allow you to keep your code organized, readable, and reusable. Whether you’re using Python’s built-in modules or writing your own, understanding how to import them properly is an essential skill for writing maintainable Python code.
Comment