as alias
- Python course
- Beginner
- Lesson 108/116
- 4 min
Learn to alias with import x as y.
The as alias
The as keyword gives a module a short name (alias). This is used to shorten long module names:
import math as m
print(m.sqrt(16)) # 4.0
print(m.pi) # 3.14159...Here the math module is loaded under the name m. Now m.sqrt and m.pi are used. The name math is not available.
This is a common technique to write shorter code.
Common aliases
The Python community has established short names for some modules. These names are used the same way across all projects:
import numpy as np
import pandas as pd
import matplotlib.pyplot as pltThese three shortcuts are standard in the data science world. np, pd and plt are recognised by everyone. Inconsistent aliases make code unreadable.
When choosing your own aliases, keep them short but meaningful.
Practice Square root with import math as m
Write import math as m. Then write print(m.sqrt(16)).
Starter code
# load the math module with alias m
# print the square root via m.sqrtSample solution
import math as m
print(m.sqrt(16))Expected output
4.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match as aliases
| Term | Meaning |
|---|---|
import math as m |
math → m |
m.sqrt(16) |
Call with short name |
as |
Alias keyword |
math (now gone) |
Not available |
2 After import math as m, what does math.sqrt(16) do?
- Works
- Raises NameError Correct answer
- Does not run but no error
- Raises ImportError
Explanation: With as m the name math becomes m; math is no longer defined.
3 Complete the as keyword
import math ____ m
print(m.sqrt(16))
import math as m
print(m.sqrt(16))
Explanation: import math as m gives math the alias m.