
Python
Python provides several ways to import modules. Each style has its purpose and appropriate use cases.
The simplest import loads an entire module.
# Import entire module
import math
# Access items with dot notation
print(math.sqrt(9)) # 3.0
print(math.pi) # 3.141592653589793
print(math.ceil(3.2)) # 4Advantages:
Disadvantages:
Import specific items directly into your namespace.
# Import specific items
from math import sqrt, pi
print(sqrt(16)) # 4.0 (no 'math.' prefix needed)
print(pi) # 3.141592653589793
# Import multiple items
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)Advantages:
Disadvantages:
Use aliases (shorter names) for modules or items.
# Alias for module
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
array = np.array([1, 2, 3])
dataframe = pd.DataFrame({"col1": [1, 2, 3]})
# Alias for specific item
from datetime import datetime as dt
from collections import Counter as Count
current_time = dt.now()
word_counts = Count("hello")When to use:
Import all public items from a module using `*`.
# Import everything from the module
from math import *
print(sqrt(25)) # 4.0
print(pi) # 3.141592653589793
print(sin(0)) # 0.0⚠️ Warning: This is generally NOT recommended because:
Exception: It's okay in small scripts or interactive environments.
Import several modules efficiently.
# One import per line (recommended)
import os
import sys
import json
from datetime import datetime
from collections import Counter
# Multiple items from one module (acceptable)
from math import sqrt, sin, cos, pi
# Multiple modules on one line (avoid - less readable)
import os, sys, json # ❌ Not recommendedSometimes you need to handle missing modules gracefully.
# Handle missing optional library
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
print("NumPy not installed. Some features won't be available.")
# Use conditionally
if HAS_NUMPY:
array = np.array([1, 2, 3])
else:
array = [1, 2, 3] # Fallback to list
# Version-specific imports
import sys
if sys.version_info >= (3, 10):
from statistics import fmean # Available in Python 3.10+
else:
def fmean(data):
return sum(data) / len(data)Pattern 1: Data Science Stack
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Now ready to work with data
data = pd.read_csv("data.csv")
X = data[["feature1", "feature2"]]
y = data["target"]
X_train, X_test, y_train, y_test = train_test_split(X, y)Pattern 2: Web Development
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import json
import os
from datetime import datetime
app = Flask(__name__)
CORS(app)
@app.route('/api/data')
def get_data():
return jsonify({"timestamp": datetime.now().isoformat()})Pattern 3: File Processing
import os
import json
import csv
from pathlib import Path
# Check if file exists
config_file = Path("config.json")
if config_file.exists():
with open("config.json") as f:
config = json.load(f)| Style | Example | Clarity | Length | Risk |
|---|---|---|---|---|
| Basic | `import math` | High | Long | Low |
| From | `from math import sqrt` | Medium | Short | Medium |
| Alias | `import numpy as np` | Medium | Short | Low |
| Wildcard | `from math import *` | Low | Short | High |
✅ DO:
# Put imports at the top of file
import os
import sys
from datetime import datetime
from collections import defaultdict
# Use meaningful aliases
import numpy as np
import pandas as pd
# Import only what you need
from math import sqrt, pi❌ DON'T:
# Don't mix import styles inconsistently
import math
from datetime import *
import os as operating_system
# Don't put imports in middle of code
def process_data():
import json # ❌ Should be at top
return json.dumps({})
# Don't use wildcard imports
from collections import *Organize imports in this standard order:
# 1. Standard library imports (built-in modules)
import os
import sys
import json
from datetime import datetime
from collections import defaultdict
# 2. Third-party imports (installed packages)
import numpy as np
import pandas as pd
import requests
# 3. Local application imports (your own modules)
from myapp.models import User
from myapp.utils import format_date
from . import helpers # Relative import
# Now your code
def main():
passReady to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward