Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are the "best practices" for using import in a Python module?
The import statement is fundamental to Python programming, but following best practices ensures clean, maintainable code. Here are the essential guidelines for using imports effectively in your Python modules.
Multiple Imports on Separate Lines
Each module should be imported on its own line for better readability ?
# Good practice
import numpy
import pandas
import matplotlib.pyplot
print("Modules imported successfully")
Modules imported successfully
However, importing multiple items from the same module on one line is acceptable ?
from os import path, getcwd, listdir
print("Current directory:", getcwd())
Current directory: /home/user
Always Place Imports at the Top
Imports should be placed at the file's beginning, following this order:
- After module comments and docstrings
- Before module globals and constants
"""
This module demonstrates proper import placement.
"""
import sys
import os
# Global constant
VERSION = "1.0"
def main():
print(f"Python version: {sys.version}")
print(f"Current OS: {os.name}")
main()
Python version: 3.x.x Current OS: posix
Import Order Convention
Follow the standard import order with blank lines separating groups ?
# Standard library imports
import sys
import os
from datetime import datetime
# Third-party imports
import numpy as np
import pandas as pd
# Local application imports
# from myproject import mymodule
print(f"Today: {datetime.now().strftime('%Y-%m-%d')}")
print(f"NumPy version: {np.__version__}")
Today: 2024-01-15 NumPy version: 1.24.3
Prefer Absolute Imports
Absolute imports are clearer and more reliable than relative imports ?
# Good - absolute imports (examples)
import json
from collections import defaultdict
from urllib.parse import urlparse
# Create a sample to show usage
data = {"name": "Python", "type": "language"}
json_string = json.dumps(data)
parsed_url = urlparse("https://python.org/docs")
print(f"JSON: {json_string}")
print(f"Domain: {parsed_url.netloc}")
JSON: {"name": "Python", "type": "language"}
Domain: python.org
Avoid Wildcard Imports
Wildcard imports (from module import *) pollute the namespace and make code unclear ?
# Bad practice (don't do this)
# from math import *
# Good practice - explicit imports
from math import sqrt, pi, sin
result = sqrt(16)
area = pi * result ** 2
print(f"Square root of 16: {result}")
print(f"Circle area (r=4): {area:.2f}")
Square root of 16: 4.0 Circle area (r=4): 50.27
Handling Circular Imports
Move imports inside functions to avoid circular import issues ?
def process_data():
# Import inside function to avoid circular imports
import json
from collections import Counter
data = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counter = Counter(data)
return json.dumps(dict(counter))
result = process_data()
print(f"Fruit counts: {result}")
Fruit counts: {"apple": 3, "banana": 2, "cherry": 1}
Best Practices Summary
| Practice | Good | Bad |
|---|---|---|
| Multiple imports | import os |
import os, sys |
| Wildcard imports | from math import sqrt |
from math import * |
| Import location | Top of file | Scattered throughout |
| Import style | Absolute imports | Relative imports |
Conclusion
Following Python import best practices improves code readability, prevents namespace pollution, and avoids common pitfalls like circular imports. Always use explicit imports, maintain proper order, and place them at the top of your modules for clean, professional code.
