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

后端 未结 3 1613
逝去的感伤
逝去的感伤 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:44

    Do you really need to use contextlib.contextmanager? If you have a custom stream you would want to use Poke's solution.

    But since you are just returning a file object, why go through all the hassle:

    def versioned(file_path, mode):
        version = calculate_version(file_path, mode)
        return open(file_path, mode)
    
    
    with versioned('test.conf', 'r') as stream:
       print stream.read()
    
    f = versioned('test.conf', 'r')
    print f.read()
    f.close()
    

    Both will work perfectly fine :)

提交回复
热议问题