as

In Python, the as keyword creates an alias or alternative name for a module, exception, or context manager. This can make your code more readable and descriptive.

Python as Keyword Examples

Here’s a quick example of using the as keyword with the import statement:

Python
>>> import numpy as np

>>> np.array([1, 2, 3])
array([1, 2, 3])

In this example, you import numpy with the alias np. Now, you can use np as a shorthand for numpy. This is particularly useful for modules with long names.

Another example is using as in exception handling:

Python
>>> try:
...     x = 1 / 0
... except ZeroDivisionError as error:
...     print(f"Caught an exception: {error}")
...
Caught an exception: division by zero

Here, the as keyword assigns the exception object to the variable error, which you can then use to access information about the exception.

Python as Keyword Use Cases

  • Simplifying module names in your code by creating shorter aliases
  • Capturing exception objects for later use in error-handling logic
  • Getting a reference to the resource being managed when using the with statements

Tutorial

Python import: Advanced Techniques and Tips

The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader