DEV Community

Cover image for The 'with' statement in python
Osinachi Chukwujama
Osinachi Chukwujama

Posted on • Edited on

3

The 'with' statement in python

The 'with' statement in python is used for resource management and exception handling. You'd most likely find it when operating with file streams. The statement ensures that the file stream process, for example, doesn't block other processes if an exception is raised, but terminates properly.

The code block below shows the 'try-finally' approach to file stream resource management.

file = open('file-path', 'w') 
try: 
    file.write('Lorem ipsum') 
finally: 
    file.close() 
Enter fullscreen mode Exit fullscreen mode

Normally, you'd want to use this method for writing to a file. But then 'with statement' offers a cleaner approach:

with open('file-path', 'w') as file: 
    file.write('Lorem ipsum') 
Enter fullscreen mode Exit fullscreen mode

The 'with statement' simplifies our file write process to just two lines.

It is also used in database CRUD processes. This example was gotten from this site

def get_all_songs():
    with sqlite3.connect('db/songs.db') as connection:
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM songs ORDER BY id desc")
        all_songs = cursor.fetchall()
        return all_songs
Enter fullscreen mode Exit fullscreen mode

Here, the 'with statement' is used to query an sqlite database and return its content.

I hope you found this useful. Please, share other uses of the 'with statement' you have encountered in the wild.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay