4

I am learning the basics of Python from Zed Shaw's Learn Python the Hard Way. I am currently at chapter 36 (Symbol review), and came across the 'as' operator. I need to search for it's uses in Python. I know this question is broad, but I didn't found anything as far on python.docs, or SO. What does this operator do?

Litwos
  • 1,278
  • 4
  • 19
  • 44
  • 2
    Check out [The `with` Statement](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement). – Kevin Jul 29 '15 at 19:33
  • 1
    Not sure why this was downvoted -- looks reasonable to me. Upvoting to compensate. – John Lockwood Jul 29 '15 at 19:38
  • Well, the 'with' statement seems like another use of 'as', so I don't understand the downvote... – Litwos Jul 29 '15 at 19:40
  • If you're learning from an online course or text, shouldn't the review be based on the material? Isn't the `as` keyword covered somewhere in there? – TigerhawkT3 Jul 29 '15 at 19:41
  • No, it says that I should search for it. I have and entire list of operators and functions I need to search and make a program. – Litwos Jul 29 '15 at 19:42
  • You're learning from material that tells you to look up other material? That seems a little odd. – TigerhawkT3 Jul 29 '15 at 19:44
  • @JohnLockwood - please don't [use your vote just to cancel out someone else's vote](http://meta.stackoverflow.com/questions/253383/upvotes-that-cancel-out-downvotes). – TigerhawkT3 Jul 29 '15 at 19:45
  • It's used in various [simple](https://docs.python.org/2/reference/simple_stmts.html) and [compound](https://docs.python.org/2/reference/compound_stmts.html) statements. – jonrsharpe Jul 29 '15 at 19:52
  • 2
    To be clear, it's not an operator at all. It's just a keyword that can be used in two distinct statements, an `import` statement and a `with` statement. – chepner Jul 29 '15 at 20:00
  • @TigerhawkT3: You can vote [however you like](http://meta.stackexchange.com/questions/209849/to-what-extent-i-am-free-with-my-voting). – Kevin Jul 29 '15 at 20:13
  • @Kevin - absolutely, but I can also encourage people to follow whatever commonly-accepted voting practices I like. :) – TigerhawkT3 Jul 29 '15 at 20:16
  • @Kevin, thanks for that. That was pretty much always the plan. :) – John Lockwood Jul 29 '15 at 23:17

2 Answers2

8

It is used to create an alias when importing modules or when using the with clause:

import pandas as pd

df = pd.DataFrame()

#####

with open(file_name, 'r') as my_file:
    my_file.readlines()
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

Its used with the with keyword:

with open("file.foo") as f:
    # Do something with f
    pass
Teyras
  • 1,262
  • 11
  • 22