Skip to content

Instantly share code, notes, and snippets.

@zonca
Created November 9, 2011 19:12
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 zonca/1352573 to your computer and use it in GitHub Desktop.
Save zonca/1352573 to your computer and use it in GitHub Desktop.
Python closing test
from contextlib import closing
class File(object):
def __init__(self, filename):
self.filename = filename
print('Created object for %s' % self.filename)
def open(self):
print('Opening %s' % self.filename)
def close(self):
print('Closing %s' % self.filename)
def myopen(filename):
f = File(filename)
f.open()
return closing(f)
if __name__ == '__main__':
filename = 'file.txt'
print('***********Using as context manager')
with myopen(filename) as f:
print(type(f))
print()
print('***********Using as a function')
f = myopen(filename)
print(type(f))
print('***********Cannot call open')
f.open()
@zonca
Copy link
Author

zonca commented Nov 9, 2011

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