Skip to content

Commit

Permalink
doc: explain cast
Browse files Browse the repository at this point in the history
  • Loading branch information
msto committed Oct 17, 2024
1 parent 6035efb commit 4ab75b7
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions fgpyo/io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,18 @@ def to_writer(path: Path, append: bool = False) -> TextIOWrapper:
>>> writer.close()
"""
mode_prefix = "w"
if append:
mode_prefix = "a"
mode_prefix: str = "a" if append else "w"

if path.suffix in COMPRESSED_FILE_EXTENSIONS:
return TextIOWrapper(
cast(IO[bytes], gzip.open(path, mode=mode_prefix + "b")), encoding="utf-8"
)
else:
# NB: the `cast` here is necessary because `path.open()` may return
# other types, depending on the specified `mode`.
# Within the scope of this function, `mode_prefix` is guaranteed to be
# either "w" or "a", both of which result in a `TextIOWrapper`, but
# mypy can't follow that logic.
return cast(TextIOWrapper, path.open(mode=mode_prefix))


Expand Down

0 comments on commit 4ab75b7

Please sign in to comment.