From fa15b61aff138ac36dc546114d374e5cde389887 Mon Sep 17 00:00:00 2001 From: Rijnder Wever Date: Mon, 16 Dec 2024 20:01:52 +0100 Subject: [PATCH] feat: handle re-opening files in binary mode internally --- mdto/mdto.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/mdto/mdto.py b/mdto/mdto.py index 6883c41..e29619a 100755 --- a/mdto/mdto.py +++ b/mdto/mdto.py @@ -459,9 +459,7 @@ def save( """Save object to an XML file. Args: - file_or_filename (str | TextIO): Path or file-object to write the object's XML representation to. - If passing a file-like object, the file must be opened - in writeable binary mode (i.e. `wb`). + file_or_filename (str | TextIO): Path or file-object to write the object's XML representation to lxml_args (Optional[dict]): Extra keyword arguments to pass to lxml's write() method. Defaults to `{xml_declaration=True, pretty_print=True, encoding="UTF-8"}`. @@ -472,6 +470,10 @@ def save( Raises: ValidationError: object is invalid MDTO """ + if hasattr(file_or_filename, "write"): + # "re-open" file in binary mode + file_or_filename = file_or_filename.buffer.raw + # validate before serialization to ensure correctness # (doing this in to_xml would be slow, and perhaps unexpected) self.validate()