Skip to content

Commit

Permalink
Add run-time type restrictions
Browse files Browse the repository at this point in the history
Previously, anything that couldn't be opened with xopen would be
returned as-is. The docstring described a type restriction on
path_or_buffer but it was not enforced.

Instead of adding a compile-time type restriction on path_or_buffer, add
run-time type restrictions by using type narrowing¹ to provide clear
context to static type checkers and raise a meaningful error if the type
is not supported.

¹ https://mypy.readthedocs.io/en/stable/type_narrowing.html
  • Loading branch information
victorlin committed Jul 5, 2023
1 parent 48b8646 commit 5209f69
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
14 changes: 10 additions & 4 deletions augur/io/file.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os
from contextlib import contextmanager
from xopen import xopen
from io import IOBase
from xopen import PipedCompressionReader, PipedCompressionWriter, xopen


@contextmanager
Expand All @@ -10,7 +12,7 @@ def open_file(path_or_buffer, mode="r", **kwargs):
Parameters
----------
path_or_buffer : str or `os.PathLike` or any I/O class
path_or_buffer
Name of the file to open or an existing IO buffer
mode : str
Expand All @@ -22,8 +24,12 @@ def open_file(path_or_buffer, mode="r", **kwargs):
File handle object
"""
try:
if isinstance(path_or_buffer, (str, os.PathLike)):
with xopen(path_or_buffer, mode, **kwargs) as handle:
yield handle
except TypeError:

elif isinstance(path_or_buffer, (IOBase, PipedCompressionReader, PipedCompressionWriter)):
yield path_or_buffer

else:
raise TypeError(f"Type {type(path_or_buffer)} is not supported.")
3 changes: 1 addition & 2 deletions tests/io/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ def test_open_file_read_error(self):
"""Try reading from an unsupported type."""
path_or_buffer = len("bogus")

# TODO: Raise a more informative error.
with pytest.raises(AttributeError, match="'int' object has no attribute 'read'"):
with pytest.raises(TypeError, match="Type <class 'int'> is not supported."):
with augur.io.file.open_file(path_or_buffer, 'r') as f:
f.read()

0 comments on commit 5209f69

Please sign in to comment.