as keyword
Updated March 15, 2026 · Keywords
keyword import exception context-manager
The as keyword in Python creates aliases for modules, captures exceptions, and binds context manager results. It’s essential for readable code when working with imports, error handling, and resource management.
Syntax
import module_name as alias
from module_name import name as alias
except Exception as variable:
with expression as variable:
How It Works
The as keyword serves three distinct purposes in Python:
1. Import Aliasing
Create shorter or more descriptive names for imported modules and objects:
# Shorten long module names
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Use plt, np, pd throughout your code
plt.plot([1, 2, 3], [4, 5, 6])
arr = np.array([1, 2, 3])
df = pd.DataFrame({'a': [1, 2, 3]})
# Rename conflicting imports
from collections import OrderedDict as OD
from collections import defaultdict as dd
# Import with alias
from os.path import join as path_join
2. Exception Capture
Bind a caught exception to a variable for inspection:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Caught error: {e}")
print(f"Error type: {type(e).__name__}")
# Caught error: division by zero
# Error type: ZeroDivisionError
# Capture the exception object
except (ValueError, TypeError) as error:
print(f"Validation failed: {error}")
# Can re-raise if needed
raise
3. Context Manager Binding
Bind the result of a context manager’s __enter__ method:
# File handling - f is bound to the file object
with open("file.txt", "r") as f:
content = f.read()
# File automatically closed here
# Multiple context managers
with open("input.txt") as inp, open("output.txt", "w") as out:
out.write(inp.read())
# Custom context managers
class Timer:
def __enter__(self):
self.start = time.time()
def __exit__(self, *args):
print(f"Took {time.time() - self.start:.2f}s")
with Timer() as t:
heavy_computation()
Common Use Cases
Import aliasing for readability
# Without alias - verbose
import matplotlib.pyplot
import seaborn
import scipy.stats
matplotlib.pyplot.plot([1, 2, 3], [1, 4, 9])
seaborn.histplot(data)
scipy.stats.norm.pdf(x)
# With alias - clean and readable
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
plt.plot([1, 2, 3], [1, 4, 9])
sns.histplot(data)
stats.norm.pdf(x)
Exception handling with context
import json
def parse_config(filename):
try:
with open(filename) as f:
return json.load(f)
except FileNotFoundError as e:
print(f"Config file missing: {e}")
return {}
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}: {e.msg}")
return {}
# The exception object gives you details
# - e.args: tuple of arguments
# - e.__class__: exception type
# - str(e): human-readable message
Resource cleanup
# Database connections
import sqlite3
conn = sqlite3.connect("data.db")
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
finally:
conn.close()
# Using context manager (preferred)
with sqlite3.connect("data.db") as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
# Connection automatically closed
Iterator binding (for loop)
# The loop variable is technically bound with as
for line in open("file.txt"):
print(line.strip())
# But explicit binding is more common
with open("file.txt") as f:
for i, line in enumerate(f, 1):
print(f"{i}: {line}", end="")
Advanced Patterns
Chained exceptions
def process_data(data):
try:
validate(data)
except ValidationError as e:
# Add context before re-raising
raise ProcessingError(f"Failed to process: {e}") from e
Multiple exception types with same handler
try:
risky_operation()
except (IOError, ValueError, RuntimeError) as e:
log_error(e)
retry_or_fail(e)
Using with multiple items (Python 3.1+)
with open("a.txt") as f1, open("b.txt") as f2:
content = f1.read() + f2.read()
# Or using nested (Python 2.7+/3.1+)
with open("a.txt") as f1:
with open("b.txt") as f2:
process(f1, f2)
See Also
- import statement — module imports
- exception handling — try/except patterns
- context managers — the with statement
- from keyword — importing specific names