Skip to content

IO classes as context managers #175

@toddrjen

Description

@toddrjen

For those who don't know, context managers are classes that can be used with python with statements. I think it would be beneficial for IO classes to be able to be used as context managers. This would provide a safe way to handle cleanup operations after running.

To create a context manager, you need two methods, __enter__ and __exit__. For us, __enter__ would probably open the file, while __exit__ would close it.

So I suggest that at the BaseIO level we implement abstract open and close methods that subclasses could re-implement to handle any cleanup. Then BaseIO would implement __enter__ and __exit__ methods that just call open and close, respectively.

So someone could just do this:

with ExampleIO(fname) as ioobj:
    data = ioobj.read()

People wouldn't need to know or care about specific cleanup operations they need to do with particular IO classes.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions