How does open() work with and without `with`?

后端 未结 3 1602
逝去的感伤
逝去的感伤 2021-02-13 11:50

I\'d like to write a function similar to open. I\'d like to be able to call it with with, but also without with.

When I use

3条回答
  •  终归单人心
    2021-02-13 12:29

    The problem is that contextmanager only provides exactly that; a context manager to be used in the with statement. Calling the function does not return the file object, but a special context generator which provides the __enter__ and __exit__ functions. If you want both the with statement and “normal” assignments to work, then you will have to have some object as the return value from your function that is fully usable and also provides the context functions.

    You can do this pretty easily by creating your own type, and manually providing the context functions:

    class MyOpener:
        def __init__ (self, filename):
            print('Opening {}'.format(filename))
        def close (self):
            print('Closing file.')
        def write (self, text):
            print('Writing "{}"'.format(text))
        def __enter__ (self):
            return self
        def __exit__ (self, exc_type, exc_value, traceback):
            self.close()
    
    >>> f = MyOpener('file')
    Opening file
    >>> f.write('foo')
    Writing "foo"
    >>> f.close()
    Closing file.
    
    >>> with MyOpener('file') as f:
            f.write('foo')
    
    Opening file
    Writing "foo"
    Closing file.
    

提交回复
热议问题