Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eder-projetos-dev/437b9c7fb5153ab4a89936576f074654 to your computer and use it in GitHub Desktop.
Save eder-projetos-dev/437b9c7fb5153ab4a89936576f074654 to your computer and use it in GitHub Desktop.
Python - Context managers
# Traditional approach
file = open("data.txt", "r")
try:
data = file.read()
# Process the data
finally:
file.close()
# Context manager
with open("data.txt", "r") as file:
data = file.read()
# Process the data
@eder-projetos-dev
Copy link
Author

How can context managers improve the efficiency of my code?

Context managers are an excellent tool for managing resources efficiently and ensuring proper cleanup. They allow you to allocate and release resources automatically by defining a setup and teardown code block. One of the most common use cases of context managers is working with files, where they handle opening and closing operations seamlessly.

https://levelup.gitconnected.com/11-tricks-that-will-make-your-life-easier-as-a-python-developer-da29e4306675

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment