Importing in Python allows you to reuse code from another module or library in your current script. This allows you to use the functions and variables defined in the module in your current script.
You can import modules in the following ways:
Using import
import math
Once a module is imported, you can then use any of its functions and variables by using the dot notation.
For example:
import math
result = math.sqrt(9)
print(result) # Output: 3.0
Using from
You can import specific functions or variables from a module using from
.
For example:
from math import sqrt
result = sqrt(9)
print(result) # Output: 3.0
You can also import multiple functions or variables at once by separating them with a comma.
For example:
from math import sqrt, pi
result = sqrt(9)
print(result) # Output: 3.0
print(pi) # Output: 3.141592653589793
Importing All Items
The *
wildcard imports everything from a module. However, this is discouraged as it can cause conflicts between similarly named items.
from math import *
result = sqrt(9)
print(result) # Output: 3.0
print(pi) # Output: 3.141592653589793
Using as
You can rename imported modules using the as
keyword. This can be useful if you want to use a shorter or more descriptive name for a module, or if you want to avoid naming conflicts with other modules or variables in your code.
import math as m
print(m.sqrt(9)) # Output: 3.0
Exploring Module Contents
Python has built-in functions that you can use to view and understand the contents of a module. This can be helpful for exploring and understanding new modules.
Using dir()
The dir()
function lists all the functions, constants, and attributes available in a module.
import math
print(dir(math))
This lists available functions, constants, and attributes in the math
module.
Using help()
The help()
function provides detailed documentation about a module or specific function.
import math
help(math) # Shows comprehensive documentation for the math module
help(math.sqrt) # Shows documentation for the sqrt function specifically
Relative Imports
When working with packages (folders containing multiple modules), you can use relative imports to import from modules in the same package or parent directories. Relative imports use dots (.) to indicate the relative location.
For example:
my_package/
__init__.py
main.py
utils.py
subfolder/
__init__.py
helper.py
In my_package/main.py, you can use:
from . import utils # Import utils.py from same directory
from .subfolder import helper # Import helper.py from subfolder
from .. import some_module # Import from parent directory (if applicable)
Note: Relative imports only work when running Python as a module or package, not as a standalone script. They're mainly used in larger projects with organized package structures.
Dynamic Imports
For more advanced use cases, Python provides the importlib
module for importing modules dynamically at runtime. This means you can import modules based on user input or conditions.
import importlib
# Import a module by name (as a string)
module_name = "math"
math_module = importlib.import_module(module_name)
print(math_module.sqrt(16)) # Output: 4.0
# Useful for importing modules based on conditions
modules_to_load = ["os", "sys", "datetime"]
loaded_modules = {}
for module_name in modules_to_load:
loaded_modules[module_name] = importlib.import_module(module_name)
# Now you can use: loaded_modules["os"].getcwd()
When to use dynamic imports
- When the module name is determined at runtime.
- For plugin systems where modules are loaded conditionally.
- In advanced frameworks and libraries.
Note: Dynamic imports are an advanced topic. As a beginner, you'll mainly use the standard import methods covered earlier.
Creating and Using Custom Modules
You can create your own modules by saving Python code in a .py
file and then importing it into other scripts.
Step 1: Create a file called my_utils.py
:
def greet(name):
"""Return a greeting message"""
return f"Hello, {name}!"
def add_numbers(a, b):
"""Add two numbers together"""
return a + b
PI = 3.14159
Step 2: Use your custom module in another file (e.g., main.py
):
import my_utils
print(my_utils.greet("World")) # Output: Hello, World!
result = my_utils.add_numbers(5, 3) # Output: 8
print(my_utils.PI) # Output: 3.14159
Or import specific functions:
from my_utils import greet, add_numbers
print(greet("Python")) # Output: Hello, Python!
print(add_numbers(10, 20)) # Output: 30
Best Practices
When working with imports in Python, following these best practices will make your code more readable and maintainable:
Import Order
Organize your imports in the following order, with blank lines between each group:
- Standard library imports: Built-in Python modules
- Third-party imports: Modules installed via pip
- Local application imports: Your own modules
# Standard library
import os
import sys
from datetime import datetime
# Third-party
import requests
import pandas as pd
# Local application
from my_utils import helper_function
from .models import User
When to Use Each Import Style
- Use
import module
when you need multiple functions from a module and want to keep the namespace clear - Use
from module import function
when you only need specific functions and use them frequently - Use
import module as alias
for modules with long names or to avoid conflicts - Avoid
from module import *
except in very specific cases (like interactive sessions)
Avoiding Circular Imports
Structure your code to prevent modules from importing each other. If you must have interdependent modules, consider:
- Moving shared code to a separate module
- Using imports inside functions instead of at the module level
- Restructuring your code architecture
# Instead of circular imports, use function-level imports when necessary
def my_function():
from some_module import needed_function # Import only when needed
return needed_function()
👉 Next tutorial: if name == "main" in Python