Created
November 9, 2011 19:12
-
-
Save zonca/1352573 to your computer and use it in GitHub Desktop.
Python closing test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
related to stackoverflow question:
http://stackoverflow.com/questions/8070259/how-to-use-python-closing-context-manager