Loading...
Loading...
import, from, packages, and fixing common errors - everything you need
Every form of the Python import statement with clear examples: import, from...import, aliases, wildcards, relative imports, and dynamic imports.
Loads an entire module. Access names using dot notation.
import os
import sys
import json
# Usage: module.name
os.path.join("/home", "user", "file.txt")
sys.exit(0)
data = json.loads('{"key": "value"}')
# Import multiple modules on separate lines (PEP 8)
import os
import sys
# NOT: import os, sys (discouraged by PEP 8)Imports specific names directly into your namespace. No dot notation needed.
from os.path import join, exists, dirname
from collections import defaultdict, Counter
from typing import List, Dict, Optional
# Usage: name directly, no prefix
join("/home", "user", "file.txt")
exists("/tmp/myfile.txt")
counts = Counter(["a", "b", "a", "c", "a"])
# Multi-line imports with parentheses
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
Union,
)Rename a module or name at import time. Useful for long names or avoiding collisions.
# Module aliases (common conventions)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import sqlalchemy as sa
# Name aliases
from datetime import datetime as dt
from collections import OrderedDict as OD
from os.path import join as pjoin
# Resolve name collisions
from myapp.models import User as AppUser
from auth.models import User as AuthUserImports all public names from a module. Generally discouraged because it pollutes your namespace and makes it hard to trace where names come from.
# Wildcard import (avoid in production code)
from math import *
print(sin(pi / 2)) # 1.0 - but where did sin and pi come from?
# What * actually imports:
# 1. If __all__ is defined: only names in __all__
# 2. If __all__ is NOT defined: all names that don't start with _
# Example __all__ in a module (mymodule.py)
__all__ = ["public_func", "PublicClass"]
def public_func():
pass
def _private_func(): # not exported by *
pass
class PublicClass: # exported by *
passUse dots to import from within the same package. Single dot means current package, double dot means parent package.
# Package structure:
# myapp/
# __init__.py
# models.py
# views.py
# utils/
# __init__.py
# helpers.py
# validators.py
# Inside myapp/views.py:
from . import models # import models from same package
from .models import User # import User from sibling module
from .utils import helpers # import helpers from sub-package
from .utils.helpers import slugify # import specific name
# Inside myapp/utils/validators.py:
from . import helpers # same package (utils)
from .helpers import slugify # sibling module
from .. import models # parent package (myapp)
from ..models import User # specific name from parent packageImport modules only when certain conditions are met, or load them by name at runtime.
# Conditional import (try faster implementation first)
try:
import ujson as json # fast C-based JSON
except ImportError:
import json # fallback to standard library
# Platform-specific import
import sys
if sys.platform == "win32":
import winreg
else:
import posixpath
# Dynamic import using importlib
import importlib
module_name = "json"
mod = importlib.import_module(module_name)
data = mod.loads('{"key": "value"}')
# Import a sub-module dynamically
sub = importlib.import_module(".models", package="myapp")
# Reload a module (useful during development)
importlib.reload(mod)