MaciekAber / pysam

Automatically exported from code.google.com/p/pysam
0 stars 0 forks source link

"context manager protocol" for Samfile #33

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
It would be great if the Samfile class could provide __enter__ and __exit__
methods. Then one could write:
with pysam.Samfile('file.bam', 'rb') as samfile:
  ... do something with samfile ...
(samfile is closed automatically)

instead of:
samfile = pysam.Samfile('file.bam', 'rb')
... do something with samfile ...
samfile.close()

I think this code (within Samfile) should be sufficient:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()
        return False

See also http://docs.python.org/reference/compound_stmts.html#the-

Original issue reported on code.google.com by marcel.m...@tu-dortmund.de on 25 May 2010 at 4:04

GoogleCodeExporter commented 8 years ago
Good idea!  In the mean time, you can use the contextlib.closing dectorator.  
E.g.:

from contextlib import closing

with closing(pysam.Samfile('file.bam', 'rb')) as samfile:
   ... do something ...

Original comment by bioinformed@gmail.com on 26 May 2010 at 11:45

GoogleCodeExporter commented 8 years ago
Thanks, didn't know about that one!

Original comment by marcel.m...@tu-dortmund.de on 26 May 2010 at 6:47

GoogleCodeExporter commented 8 years ago
great idea, added to dev-0.3

Original comment by andreas....@gmail.com on 18 Jul 2010 at 6:15

GoogleCodeExporter commented 8 years ago
Great, thanks!

Original comment by marcel.m...@tu-dortmund.de on 19 Jul 2010 at 2:17