Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Using the as keyword in Python

I'm going through the beginner Python course and I just don't understand the "as" keyword at all or when I would need to use it. Is there anyone that could explain it in more detail please?

The as keyword is used for aliasing in Python.

for example, import pandas as pd

pd.dataframe...

it can be used to take something and give it a simpler name for reuse. Not a requirement but helpful to keep things clean and simple.

another example would be:

BEFORE:
f = open(file)
f.read()
f.close

AFTER:

with open(file) as f:
    f.read()

So as you can see, it's not essential but it help in being slightly more pythonic by keeping thing concise and clean. However, it is not always of benefit. In python readability is highly valued so if you us an as statement and use something that is unclear or unable to figure out the reference, someone in the future reading your code might be confused or waste time trying to figure out what you were doing. So yes, it's beneficial and I've used it but when using it, ask yourself is this making it less readable and ambiguous or can someone coming into it for the first time looking at your code and easily understand what you were thinking!