Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor typing_utils.narrow #352

Merged
merged 7 commits into from
Jul 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions explainaboard/loaders/file_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ def validate(self):
def load_raw(
self, data: str | DatalabLoaderOption, source: Source
) -> FileLoaderReturn:
data = narrow(data, str)
data = narrow(str, data)
if source == Source.in_memory:
file = StringIO(data)
lines = list(csv.reader(file, delimiter='\t', quoting=csv.QUOTE_NONE))
Expand Down Expand Up @@ -396,7 +396,7 @@ def validate(self):
def load_raw(
self, data: str | DatalabLoaderOption, source: Source
) -> FileLoaderReturn:
data = narrow(data, str)
data = narrow(str, data)
if source == Source.in_memory:
return FileLoaderReturn(data.splitlines())
elif source == Source.local_filesystem:
Expand Down Expand Up @@ -431,7 +431,7 @@ def add_sample():
field.src_name: [] for field in self._fields
} # reset

max_field: int = max([narrow(x.src_name, int) for x in self._fields])
max_field: int = max([narrow(int, x.src_name) for x in self._fields])
for line in raw_data.samples:
# at sentence boundary
if line.startswith("-DOCSTART-") or line == "" or line == "\n":
Expand All @@ -447,7 +447,7 @@ def add_sample():

for field in self._fields:
curr_sentence_fields[field.src_name].append(
self.parse_data(splits[narrow(field.src_name, int)], field)
self.parse_data(splits[narrow(int, field.src_name)], field)
)

add_sample() # add last example
Expand All @@ -458,7 +458,7 @@ class JSONFileLoader(FileLoader):
def load_raw(
self, data: str | DatalabLoaderOption, source: Source
) -> FileLoaderReturn:
data = narrow(data, str)
data = narrow(str, data)
if source == Source.in_memory:
loaded = json.loads(data)
elif source == Source.local_filesystem:
Expand Down Expand Up @@ -524,7 +524,7 @@ def replace_labels(cls, features: dict, example: dict) -> dict:
def load_raw(
self, data: str | DatalabLoaderOption, source: Source
) -> FileLoaderReturn:
config = narrow(data, DatalabLoaderOption)
config = narrow(DatalabLoaderOption, data)
dataset = load_dataset(
config.dataset, config.subdataset, split=config.split, streaming=False
)
Expand Down Expand Up @@ -594,7 +594,7 @@ def __init__(
def load_raw(
cls, data: str | DatalabLoaderOption, source: Source
) -> FileLoaderReturn:
data = narrow(data, str)
data = narrow(str, data)
if source == Source.in_memory:
return FileLoaderReturn(data.splitlines())
elif source == Source.local_filesystem:
Expand Down
30 changes: 22 additions & 8 deletions explainaboard/utils/typing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,27 @@ def unwrap_generator(obj: Optional[Iterable[T]]) -> Generator[T, None, None]:
yield from obj


NarrowType = TypeVar("NarrowType")
def narrow(subcls: type[T], obj: Any) -> T:
"""Narrow (downcast) an object with a type-safe manner.

This function does the same type casting with ``typing.cast()``, but additionally
checks the actual type of the given object. If the type of the given object is not
castable to the given type, this funtion raises a ``TypeError``.

def narrow(obj: Any, narrow_type: type[NarrowType]) -> NarrowType:
"""returns the object with the narrowed type or raises a TypeError
(obj: Any, new_type: type[T]) -> T"""
if isinstance(obj, narrow_type):
return obj
else:
raise TypeError(f"{obj} is expected to be {narrow_type}")
:param subcls: The type that ``obj`` is casted to.
:type subcls: ``type[T]``
:param obj: The object to be casted.
:type obj: ``Any``
:return: ``obj`` itself
:rtype: ``T``
:raises TypeError: ``obj`` is not an object of ``T``.
"""
if not isinstance(obj, subcls):
raise TypeError(
f"{obj.__class__.__name__} is not a subclass of {subcls.__name__}"
)

# NOTE(odashi): typing.cast() does not work with TypeVar.
# Simply returning the obj is correct because we already narrowed its type
# by the previous if-statement.
return obj
4 changes: 2 additions & 2 deletions explainaboard/utils/typing_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
class TestTypingUtils(unittest.TestCase):
def test_narrow(self):
a: str | int = 's'
self.assertEqual(narrow(a, str), a)
self.assertRaises(TypeError, lambda: narrow(a, int))
self.assertEqual(narrow(str, a), a)
self.assertRaises(TypeError, lambda: narrow(int, a))