Home ยป How to use python closing context manager?

How to use python closing context manager?

f = open(‘file.txt’)
print(type(f))
<type ‘file’>

with open(‘file.txt’) as f:
    print(type(f))
<type ‘file’>

def myopen(filename):
    f = File(filename)
    f.open()
    return closing(f)

with myopen(‘file.txt’) as f:
    print(type(f))
<class ‘__main__.File’>

f = myopen(filename)
print(type(f))
<class ‘contextlib.closing’>

class File(object):
   # … all the methods you already have …

   # context management
   def __enter__(self):
       return self
   def __exit__(self, *exc_info):
       self.close()

Add Comment

Click here to post a comment

Your email address will not be published. Required fields are marked *