PY

Modules & Imports

Python · 8 entries

Basic Imports

syntax
import module
from module import name
import module as alias
example
import json
from pathlib import Path
from collections import defaultdict, Counter
import numpy as np  # common alias convention

data = json.dumps({"key": "value"})
print(data)
output
{"key": "value"}

Note Convention: standard library imports first, then third-party, then local. Separate groups with a blank line. Use isort to auto-format.

__name__ == '__main__' Guard

syntax
if __name__ == '__main__':
    ...
example
# my_module.py
def compute_tax(price: float, rate: float = 0.08) -> float:
    return price * rate

if __name__ == "__main__":
    # Only runs when executed directly, not when imported
    result = compute_tax(100)
    print(f"Tax: ${result:.2f}")
output
Tax: $8.00

Note This guard prevents code from running when the module is imported by another file. Essential for reusable modules that also serve as scripts.

__all__ (Controlling Exports)

syntax
__all__ = ['name1', 'name2']
example
# utils.py
__all__ = ["format_price", "validate_email"]

def format_price(amount: float) -> str:
    return f"${amount:,.2f}"

def validate_email(email: str) -> bool:
    return "@" in email

def _internal_helper():  # not exported
    pass

Note __all__ defines what 'from module import *' exports. It does not prevent direct imports of unlisted names. Prefix internal helpers with underscore by convention.

Relative Imports

syntax
from . import sibling
from .. import parent_module
from .sibling import name
example
# project/
# ├── __init__.py
# ├── models.py
# └── services/
#     ├── __init__.py
#     └── auth.py

# Inside services/auth.py:
# from ..models import User
# from . import helpers

Note Relative imports only work inside packages (directories with __init__.py). They fail if you run the file directly as a script. Use -m flag: python -m package.module.

Virtual Environments

syntax
python -m venv env_name
source env_name/bin/activate
example
# Create a virtual environment
# python -m venv .venv

# Activate (macOS/Linux)
# source .venv/bin/activate

# Activate (Windows)
# .venv\Scripts\activate

# Install packages
# pip install requests

# Save dependencies
# pip freeze > requirements.txt

# Deactivate
# deactivate

Note Always use virtual environments to isolate project dependencies. Python 3.12+ also has improved error messages when venv is not activated.

Package Structure

syntax
package/
  __init__.py
  module.py
  subpackage/
    __init__.py
example
# myapp/
# ├── __init__.py          # makes it a package
# ├── config.py
# ├── models/
# │   ├── __init__.py
# │   └── user.py
# └── utils/
#     ├── __init__.py
#     └── formatting.py

# In __init__.py, expose public API:
# from .config import Settings
# from .models.user import User

Note __init__.py runs when the package is imported. Use it to define the package's public interface. It can be empty for simple packages.

Dynamic Imports

syntax
import importlib
mod = importlib.import_module('name')
example
import importlib

# Import module by string name
json_mod = importlib.import_module("json")
result = json_mod.dumps({"dynamic": True})
print(result)

# Reload a module during development
# importlib.reload(my_module)
output
{"dynamic": true}

Note Dynamic imports are useful for plugin systems and lazy loading. importlib.reload() re-executes the module but existing references to old objects are not updated.

pip & Dependency Management

syntax
pip install package
pip install -r requirements.txt
example
# Install a package
# pip install requests

# Install specific version
# pip install requests==2.31.0

# Install from requirements file
# pip install -r requirements.txt

# Show installed packages
# pip list

# Show details about a package
# pip show requests

Note Consider using pip-tools, poetry, or uv for reproducible dependency management. pip freeze captures transitive deps, which can be fragile across platforms.