3

I've seen it many times but never understood what the as command does in Python 3.x. Can you explain it in plain English?

hcarver
  • 7,126
  • 4
  • 41
  • 67

2 Answers2

9

It's not a command per se, it's a keyword used as part of the with statement:

with open("myfile.txt") as f:
    text = f.read()

The object after as gets assigned the result of the expression handled by the with context manager.

Another use is to rename an imported module:

import numpy as np

so you can use the name np instead of numpy from now on.

The third use is to give you access to an Exception object:

try:
    f = open("foo")
except IOError as exc:
    # Now you can access the Exception for more detailed analysis
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • thanks but i don't know what do the `with` statement do. Can you explain? –  Sep 29 '13 at 16:14
  • I can't find any technical reference for the "as" statement in the official Python docs. Anyone know of one? – Brian H. Feb 15 '16 at 05:49
  • @BrianHVB: Since it isn't a "standalone" keyword, you need to look at the documentation of `with`, `try/except` and `import` – Tim Pietzcker Feb 15 '16 at 06:19
5

It is a keyword used for object naming in several cases.

from some_module import something as some_alias
# `some_alias` is `some_module.something`

with open("filename") as f:
    # `f` is the file object `open("filename")` returned

try:
    Nonsense!
except Exception as e:
    # `e` is the Exception thrown
Kabie
  • 10,489
  • 1
  • 38
  • 45