Definition
Three situations come up constantly when writing Python. A useful module carries a long name, to be retyped on every line. An error is caught, but nothing tells you which one it was or why. A file is opened, and there still has to be a way to read from it. All three ask the same question: under what name do you handle what was just obtained?
as is Python's answer. It attaches a local name to whatever was designated right before it, and that name becomes usable in the scope that follows. The mechanism is tiny, but it spares three awkward workarounds that would otherwise turn up in almost every file.
Here are the three positions side by side, outside of any program, to make the shape recognisable.
import pandas as pd # rename an imported module
except ValueError as error: # name the caught exception
with open("data.csv") as handle: # name the opened resourceThey look nothing alike, and yet the intent is the same: giving a short name to something that has none.
Renaming an import
This is the most visible use, and the easiest to justify. Repeating matplotlib.pyplot in front of every call in a plotting script makes the lines longer without teaching anyone anything. plt says the same thing in three letters.
Some libraries have an alias so widespread that it is part of their identity: pd for pandas, np for numpy, plt for matplotlib. These are conventions, and that is where their value lies: a reader running into pd.read_csv knows where the function comes from without scrolling back to the top of the file. Inventing your own alias breaks that reflex.
The second service is less visible: as settles name collisions. Two modules each exposing a load function cannot live together as they are, the second import silently overwriting the first. Renaming one of them at import time removes the ambiguity, and the code then says which of the two it calls.
Naming an exception
An except block written without as does catch the error, but it hands you nothing. You know an exception of type ValueError went through; you have no idea which value caused it, and the message Python had written is lost.
as puts that object at your disposal, under the name of your choice. The difference shows the day an incident happens: a log that keeps repeating "entry rejected" teaches nothing, whereas a log that says which entry settles the matter in a minute.
try:
amount = int(entry)
except ValueError as error:
log(f"Entry rejected: {error}")The object named this way holds the error message and, depending on its type, attributes filled in for you: the name of the missing file, the key absent from the dictionary, the index out of range.
That name disappears when the block ends: Python runs the equivalent of a del to release the memory held by the trace. Reading it just afterwards raises a NameError, even though the assignment sits three lines above. If the value has to survive, copy it into another variable inside the except.
Naming a resource
An open file has to be closed, and so does a connection. Forgetting to close causes no immediate error: the program works, then runs out of open file handles after a few thousand iterations.
with entrusts opening and closing to a context manager, and as names whatever that manager produces: the open file, the established connection, the acquired lock. Closing is guaranteed on leaving the block, even when an error interrupts the work, which makes the try and finally pair unnecessary here.
Since Python 3.10, as occupies a fourth position: the match statement, where it names part of the recognised pattern. The intent does not change, but this form only turns up in recent code.
A keyword, not a function
as belongs to the grammar of the language, just like if or return, and two practical consequences follow from that.
The first: the name is reserved. Writing as = 3 does not create a badly chosen variable, it raises a SyntaxError and the program refuses to start.
The second is more useful. as only works in the positions the grammar provides for: renaming a value after the fact goes through an ordinary assignment, short = a_very_long_name. That limit becomes a landmark when reading unfamiliar code, since an as always sits on an import, an exception, a context or a pattern, never in the middle of a computation.
Frequently asked questions
Should long imports always be renamed?
No, only two cases justify it: the alias is a convention everyone recognises, or the full name genuinely weighs the reading down because it comes back on every line. Otherwise the original name stays the clearest, and an alias invented for a well-known library has the opposite effect of the one intended.
Does the name given by as survive the block?
It depends on the context, and the difference is surprising. After a with, the variable still exists, but the resource it points to is closed: reading it again serves no purpose. After an except, the name itself has been deleted, and reading it raises a NameError.
Can several items be renamed in one import?
Yes, each imported item can take its own alias on the same line, for instance from module import a as x, b as y. Readability sets its own limit, though: beyond two or three renamings, the line turns into a dictionary to decipher, and it is better to split it.