[Biopython] PDBIO.save(fh) in BioPython 1.80 always closes the file handle

Adam Sjøgren <[email protected]> Wed, 07 Dec 2022 13:33:31 +0100
Newsgroups gmane.comp.python.bio.general
Organization koldfront - analysis & revolution, Copenhagen, Denmark
Message-ID <[email protected]>
  Hi,


We are testing upgrading from BioPython 1.79 to 1.80, and have hit a
change in PDBIO.save(fh).

Our code is converting from MMCIF format to PDB via a StringIO object,
like this:

            # Load structure from mmcif file
            parser = MMCIFParser()
            structure = parser.get_structure(ac, cif)
            # Generate PDB object into StringIO object
            io = PDBIO()
            io.set_structure(structure)
            tmp = StringIO()
            io.save(tmp)
            tmp.seek(0)
            # Get content
            content = tmp.read().encode('utf-8')

Due to the this commit:

    commit be77131200821bb01254c87fb14ee1bf6c81dd4b
    Author: João Rodrigues <[email protected]>
    Date:   Thu Aug 5 01:53:42 2021

        Improvements to PDBIO (#3679)

        - Make error messages clearer by specifying the offending atom(s).
        - Slight refactoring to access class attributes directly instead of using get_xxx() methods.

where PDBIO.save() instead of "tasting" the argument and deciding
whether to close the file handle or not, it is instead doing "with
fhandle:", so the filehandle you pass in is always closed before
returning.

For a StringIO file handle that is not great, because, as the
io.StringIO documentation says:

  "The text buffer is discarded when the close() method is called."
   · https://docs.python.org/3/library/io.html#io.StringIO

Is this side effect intended, and is there a workaround?

We could of course write the PDB-file to disk and read it from there
again, but that seems kind of ugly compared to keeping it all in
StringIO memory.


  Best regards,

    Adam

-- 
 "I pragmatically turn my whims into principles!"           Adam Sjøgren
                                                       [email protected]

_______________________________________________
Biopython mailing list  -  [email protected]
https://mailman.open-bio.org/mailman/listinfo/biopython