Python AS Keyword


Python - as keyword

as keyword is used to create an alias in Python.

as keyword is generally used to create alias in the following scenarios.

  • To create an alias for module name in import statement.
  • To create an alias for sub-module name in import statement.
  • To create an alias for resource in with resource statement.
  • To create an alias for exception.

The syntax to use as keyword to create an alias for importing a module is

import <module_name> as <alias_name>

The syntax to use as keyword to create an alias for importing a sub-module is

from <module_name> import <sub_module_name> as <alias_name>

The syntax to use as keyword to create an alias for a resource is

with <resource> as <alias_name>

The syntax to use as keyword to create an alias for importing a module is

except <exception_name> as <alias_name>

Example 1: Create Alias for Module

In this example, we will create an alias for module numpy in the import statement with alias name np.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7])
print(a)

Output

[4 5 3 7]

Example 2: Create Alias for Sub-Module

In this example, we will create an alias for sub-module scimath in the import statement with alias name smath.

Python Program

from numpy.lib import scimath as smath

print(smath.log(10))

Output

2.302585092994046

Example 3: Create Alias for Module

In this example, we will read a file using open() function and store its reference in a variable using with statement and as keyword as shown below.

Python Program

with open('sample.txt') as myfile:
    fileContents = myfile.read()

print(fileContents)

sample.txt

Hi User!
Welcome to Python Examples.
Continue Exploring.

Output

Hi User!
Welcome to Python Examples.
Continue Exploring.

Example 4: as in Except clause

In this example, we will create an alias for module numpy in the import statement with alias name np.

Python Program

try:
    with open('no_file.txt') as myfile:
        fileContents = myfile.read()
except FileNotFoundError as ex:
    print(ex)

Output

[Errno 2] No such file or directory: 'no_file.txt'

Summary

In this tutorial of Python Examples, we learned how to use Python as keyword to create an alias in different scenarios, with the help of examples.