Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Modules Import BasicsCreating ModulesImport StatementsRelative ImportsImport PathsPackages StructureNamespace PackagesPip & DependenciesModule Performance
Python/Modules Packages/Import Statements

📝 Import Statements — Syntax and Best Practices

Python provides several ways to import modules. Each style has its purpose and appropriate use cases.


🎯 Basic Import Statement

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))    # 4

Advantages:

  • Clear origin of functions (math.sqrt shows it comes from math)
  • Avoids name conflicts

Disadvantages:

  • Need to type module name every time

💡 From-Import Statement

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:

  • Shorter code (no module prefix)
  • Clear what you're using

Disadvantages:

  • Less clear where items come from
  • Can cause name conflicts if multiple modules have same item

🎨 Import with Alias

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:

  • Common data science libraries (numpy as np, pandas as pd)
  • Long module names
  • Avoiding name conflicts

📦 Import Everything (Wildcard)

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:

  • Unclear where functions come from
  • Can cause hidden name conflicts
  • Makes code harder to understand
  • Pollutes namespace

Exception: It's okay in small scripts or interactive environments.

🔄 Multiple Import Statements

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 recommended

🏗️ Conditional Imports

Sometimes 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)

💻 Real-World Import Patterns

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)

📊 Import Style Comparison

StyleExampleClarityLengthRisk
Basic`import math`HighLongLow
From`from math import sqrt`MediumShortMedium
Alias`import numpy as np`MediumShortLow
Wildcard`from math import *`LowShortHigh

🔑 Best Practices

✅ 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 *

🎓 Import Organization

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():
    pass

🔑 Key Takeaways

  • ✅ `import module` loads entire module (most common, clearest)
  • ✅ `from module import item` imports specific items directly
  • ✅ Use aliases for long names: `import numpy as np`
  • ✅ Avoid wildcard imports (`from module import *`)
  • ✅ Put all imports at the top of the file
  • ✅ Organize imports: standard library, then third-party, then local

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn