Skip to content

Instantly share code, notes, and snippets.

@dmiro
Created May 21, 2014 13:43
Show Gist options
  • Select an option

  • Save dmiro/1aea14572d4d0c6a84bb to your computer and use it in GitHub Desktop.

Select an option

Save dmiro/1aea14572d4d0c6a84bb to your computer and use it in GitHub Desktop.
Python clausule With and Context Managers
"""
CHEAT 2: clausule With and Context Managers
In python the with keyword is used when working with unmanaged resources (like file streams).
It is similar to the using statement in VB.NET and C#
It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running,
even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.
https://docs.python.org/2/whatsnew/2.6.html#pep-343-the-with-statement
"""
class Test:
def __init__(self, name):
self._name = name
def __del__(self):
print "Bye bye"
def __enter__(self):
print "Enter"
return self
def __exit__(self, type, value, traceback):
print "Exit"
def say_hello(self):
print "Hello %s!" % self._name
# Test
with Test("David") as test:
test.say_hello()
with Test("Everybody") as test:
test.say_hello()
# Result
"""
Enter
Hello David!
Exit
Enter
Bye bye
Hello Everybody!
Exit
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment