glourencoffee / pycvm

Python library for processing data from CVM
MIT License
2 stars 0 forks source link

Create context-managed classes for reader functions #19

Closed glourencoffee closed 2 years ago

glourencoffee commented 2 years ago

Description

The functions fca_reader() and dfpitr_reader() return a generator that lazily reads a file passed to them as an argument. Or, if a file path is passed instead, a file is opened behind the scenes:

reader = cvm.fca_reader('myfca.zip') # calls zipfile.ZipFile('myfca.zip')
fca    = next(reader)

This simplifies the caller side, because the caller doesn't have to import zipfile and create a ZipFile on their own:

import zipfile

with zipfile.ZipFile('myfca.zip') as archive:
    reader = cvm.fca_reader(archive)
    fca    = next(reader)

But the problem is that "myfca.zip" is not closed properly, and since the file object is not available to the caller, the caller can't even close it on their own. A better approach is to subclass ZipFile as a class for each reader:

with cvm.FCAFile('myfca.zip') as file:
    fca = next(file)

with cvm.DFPITRFile('mydfp.zip') as file:
    dfpitr = next(file)