1.

For what purpose(s) is Python’s ‘as’ keyword used?

Answer»

<P>There are three distinct SITUATIONS in Python script where ‘as’ keyword is appropriately used.

  1. to define alias for imported package, module or function.
Alias for module in a package >>> from os import path as p alias for a module >>> import math as m >>> m.SQRT(100) 10.0 alias for imported function >>> from math import sqrt as underroot >>> underroot(100) 10.0
  1. to define a context manager variable:
>>> with open("file.txt",'w') as f: f.write("HELLO")
  1. as argument of exception:

When an exception occurs inside the try block, it may have an ASSOCIATED value known as the argument defined after exception type with ‘as’ keyword. The type of the argument depends on the exception type. The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args.

>>> def divide(x,y): try: z=x/y print (z) except ZeroDivisionError as err: print (err.args) >>> divide(10,0) ('division by zero',)


Discussion

No Comment Found