Python While Listening To Every Cover of Khaled's "Aicha" in the World - Resource Management

Python While Listening To Every Cover of Khaled's "Aicha" in the World - Resource Management

Resource Management

Computers need memory, storage and power. The resources of a computer need to be managed. Just like the resources of a Susanna - Susanna's need adequate amount of rest, exercise and nourishing food or else they will go insane (oops). 

A context manager can help take care of a computer, just like a healthy, balanced lifestyle can help take care of a Susanna (oops). A context manager takes care of assigning and releasing resources. 

Such as files and database connections.

A golden sunset desert. Text reads: context managers.

The With Statement

The with statement in Python allows us to make sure that our files are properly closed after use.

So what does a context manager have to do with resource management?

The with statement allows us to skip opening and closing the file manually - okay so what I have known this for months? AH. I SEE. IT IS IMPOSSIBLE THAT WE WILL FORGET TO CLOSE OUR FILE WITH THE 'WITH' STATEMENT. OH SO COOL!

I re-wrote some code that was written without a context manager with a context manager and it was so much more efficient. Let's have a look at it. Here we go:
#  With no context management
try:
  open_file = open('file_name.txt', 'r')
  print(open_file.read())
finally:
  open_file.close()

# With context management
with open("file_name.txt", "r") as file:
  print(file.read())

Class Based Context Managers

Hmmm, I need a little break. These will come next. In my next session. 

Whether that's next week or this weekend. Context managers are coming back soon.

Thank you!!!

Comments

Popular posts from this blog

Hello World

Yosemite

Where To Hide A Star