Skip to content

IO classes as context managers #175

Open

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.

Activity

  1. tbekolay commented on Jul 21, 2014

    @tbekolay

    +1, this would be great.

  2. samuelgarcia commented on Jul 21, 2014

    @samuelgarcia
    Contributor

    It sounds good.

  3. rproepp commented on Jul 22, 2014

    @rproepp
    Member

    Sure, we can do it in the next round of IO changes.

    But it will change the way IOs are used: Currently IOs open and close files automatically. So existing code would not work anymore because it doesn't call open() and it would not clean up because it doesn't call close().

  4. toddrjen commented on Jul 25, 2014

    @toddrjen
    ContributorAuthor

    That would be necessary anyway if we are going to support iteration as in #177.

  5. rproepp commented on Jul 25, 2014

    @rproepp
    Member

    True. I think there is consensus since we are changing the API anyway. We can include it in the next round of IO changes. There are only two IOs left for this round, so we could start with that soon.

  6. added this to the 0.4 milestone on Feb 5, 2015
  7. modified the milestones: , 0.4 on Jul 4, 2016
  8. JuliaSprenger commented on Jan 8, 2019

    @JuliaSprenger
    Member

    Can this be implemented in the basefromrawio so all IOs can be used as context managers? Currently only the NixIO has this feature.

  9. samuelgarcia commented on Jan 8, 2019

    @samuelgarcia
    Contributor

    I think yes.
    Let see after #461

  10. added a commit that references this issue on Nov 30, 2026
    3b125d5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions