as keyword in Python plays a important role in simplifying code, making it more readable and avoiding potential naming conflicts. It is mainly used to create aliases for modules, exceptions and file operations. This powerful feature reduces verbosity, helps in naming clarity and can be essential when multiple modules have similar names or when managing file operations.
Example:
Python
# Using `as` to alias an imported module
import math as m
# Using a function from the math module with the alias
print(m.sqrt(16))
Examples of using the as keyword
Example 1: Create Alias for the module
The most common use of the as keyword is to assign a short alias to a module when importing it. This makes the code cleaner, especially when working with long module names. It also helps in preventing conflicts with existing variables in our code.
Python
# Import random module with alias
import random as geek
# Using random module with alias to generate random numbers
a = geek.randint(5, 10)
b = geek.randint(1, 5)
# Printing the generated random numbers
print(a,b)
Explanation: In this example, the random module is imported with the alias geek. This simplifies the code and we use geek instead of random to generate random numbers.
Example 2: as with a file
as keyword in file operations allows using the open() function within a with statement, ensuring files are automatically closed after the operation.
Python
# Using 'as' keyword with 'open' function
with open('sample.txt') as geek:
# Reading text with alias
geek_read = geek.read()
# Printing the text read from the file
print("Text read with alias:")
print(geek_read)
Output:
Text read with alias:
Hello Geeks For Geeks
Explanation: This code opens a file called sample.txt using the open function and assigns it to the alias geek. Then, it reads and prints the contents of the file.
Example 3: as in Except clause
as keyword in the except clause allows assigning the caught exception to a variable for more specific handling or inspection.
Python
# Demonstrating 'as' keyword with exception handling
try:
import maths as mt
except ImportError as err:
print(err)
try:
# With statement with 'geek' alias
with open('geek.txt') as geek:
# Reading text with alias
geek_read = geek.read()
# Printing the read text
print("Reading alias:")
print(geek_read)
except FileNotFoundError as err2:
print('No file found')
Output:
No module named 'maths'
No file found
Explanation: In this case, the ImportError and FileNotFoundError exceptions are caught using the as keyword, and their respective details are assigned to the variables err and err2. This allows for clearer error messages and better debugging.