Python Tutorial

Python as Keyword: Aliases for Modules, Exceptions and with Statements

TGTeam GyaniPanditNovember 29, 20263 min read

The as keyword in Python creates an alias, a second, usually shorter, name for something. You will see it in three places: when importing modules (import numpy as np), when catching exceptions (except ValueError as e), and in with statements (with open(...) as f). This page explains each use with real outputs.

1. Giving a Module a Short Name

import math as m

print(m.sqrt(16))
print(m.pi)

Output:

4.0
3.141592653589793

After import math as m, you use m instead of math. Note that the original name math is not available in this case; only the alias is.

Python as keyword module alias example

Popular conventions

Some aliases are so common that almost every Python programmer uses them. Following them makes your code easier for others to read:

Import Library
import numpy as np NumPy (numbers and arrays)
import pandas as pd pandas (data tables)
import matplotlib.pyplot as plt Matplotlib (charts)
import seaborn as sns Seaborn (statistical charts)
import tensorflow as tf TensorFlow (machine learning)

2. Renaming a Single Imported Item

from math import factorial as fact
print(fact(5))

import datetime as dt
print(dt.date(2026, 11, 29))

Output:

120
2026-11-29

This is useful when a name is long, or when two modules have functions with the same name and you need to tell them apart.

3. Catching an Exception Object

try:
    1 / 0
except ZeroDivisionError as err:
    print("Error:", err)

Output:

Error: division by zero

as err stores the exception object, so you can print its message or log it.

4. In with Statements

with open("notes.txt", "w") as f:
    f.write("Hello")

Here as f gives a name to the opened file. The with statement closes the file automatically when the block ends, even if an error occurs.

5. In match-case Patterns (Python 3.10+)

match (3, 4):
    case (x, y) as point:
        print(point, x + y)

Output:

(3, 4) 7

See Python structural pattern matching for more.

Good Practices

  • Use the standard aliases (np, pd, plt) rather than inventing your own.
  • Do not create aliases that make code harder to understand, such as import os as x.
  • Avoid aliases that hide built-in names, like import math as list.

Frequently Asked Questions

What does “as” do in Python?

It gives a new name (alias) to a module, an imported item, an exception, a with resource or a matched pattern.

Can I still use the original module name after “import math as m”?

No. Only m is defined. Write import math separately if you also need the full name.

Why do people write “import numpy as np”?

It is a widely followed convention that keeps code short and familiar to other programmers.

Related: Accessing tuple elements in Python

Turn reading into skillsCertificate courses in AI, Data Science and programming.
Explore Courses