Skip to content

Commit 541ab16

Browse files
authored
Allow Reader/Writer to be context managers (#311)
* Allow Reader/Writer to be context managers By adding __enter__ and __exit__ methods to the Reader and Writer classes, they can now be used as context managers. Also added a test to make sure the Reader context manager works correctly. Did not add a test to do the same with Writer, because trying to write to a closed Writer results in a segfault rather than raising an exception that can be checked by pytest. * Remove enter/exit from Writer not necessary because they will be inherited
1 parent 8624896 commit 541ab16

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

cyvcf2/cyvcf2.pyx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,12 @@ cdef class VCF(HTSFile):
293293
if threads is not None:
294294
self.set_threads(threads)
295295

296+
def __enter__(self):
297+
return self
298+
299+
def __exit__(self, type, value, tb):
300+
self.close()
301+
296302
def set_threads(self, int n):
297303
v = hts_set_threads(self.hts, n)
298304
if v < 0:

cyvcf2/tests/test_reader.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1410,3 +1410,9 @@ def test_num_records_no_index(path):
14101410
vcf = VCF(os.path.join(HERE, path))
14111411
with pytest.raises(ValueError, match="must be indexed"):
14121412
vcf.num_records
1413+
1414+
def test_reader_context_manager():
1415+
with VCF(VCF_PATH) as vcf:
1416+
pass
1417+
with pytest.raises(Exception, match="attempt to iterate over closed"):
1418+
next(vcf)

0 commit comments

Comments
 (0)