Master Python Imports: Best Practices for Clean and Safe Code
This guide explains six essential Python import techniques—including using full module imports, aliases, selective imports, avoiding wildcard imports, checking existing names, and leveraging the __all__ attribute—to help you write clearer, conflict‑free code.
1. Import the whole module
Import the entire module instead of individual functions or classes, then access its contents via the module name.
import math
result = math.sqrt(16)2. Use an alias
When a module name is long or may clash with other names, assign it a short alias.
import numpy as np
array = np.array([1, 2, 3])Aliases also help disambiguate functions with the same name from different modules.
from html import escape as html_escape
from xml.sax import saxutils as xml_escape3. Import only what you need
Import specific functions or classes rather than using from module import *, reducing namespace pollution.
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)4. Avoid from module import *
Wildcard imports pull all public names into the current namespace, increasing the risk of name collisions; use them only in interactive sessions for quick testing.
# Not recommended
from os import *
from sys import *5. Check for existing names
Before importing a new name, verify that the same identifier does not already exist in the current scope.
if 'name' not in locals():
from some_module import name
else:
print("Name 'name' already exists")6. Use the built‑in __all__ mechanism
If you maintain a module, define an __all__ list to explicitly specify which names are exported when from module import * is used.
# some_module.py
__all__ = ['function_a', 'function_b']
def function_a():
pass
def function_b():
pass
def internal_function():
passExample of avoiding name conflicts by importing a module with an alias and preserving the built‑in open function.
import os as os_module
my_open = open # Save built‑in open
def open(filename):
"""Custom file‑open wrapper"""
return my_open(filename, 'r')
file_descriptor = os_module.open('path/to/file', os_module.O_RDONLY)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
