Skip to content

Commit 6c19d08

Browse files
authored
Add mypy to the commit hooks and address typing issues (#72)
* Add mypy to the commit hooks and address typing issues * Ignore `DataFrameType` and `SeriesType`
1 parent 9f37373 commit 6c19d08

8 files changed

Lines changed: 37 additions & 24 deletions

File tree

‎.pre-commit-config.yaml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ repos:
1010
- id: isort
1111
additional_dependencies: [toml]
1212
exclude: examples/*
13+
# types
14+
- repo: https://github.com/pre-commit/mirrors-mypy
15+
rev: 'v0.940'
16+
hooks:
17+
- id: mypy
18+
language_version: python3
19+
args: [--no-strict-optional, --ignore-missing-imports, --show-traceback, --install-types, --non-interactive]
20+
exclude: docs/*
1321
# code style
1422
- repo: https://github.com/python/black
1523
rev: 22.3.0

‎merlin/core/dispatch.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,12 @@ def inner2(*args, **kwargs):
7272

7373

7474
if HAS_GPU:
75-
DataFrameType = Union[pd.DataFrame, cudf.DataFrame]
76-
SeriesType = Union[pd.Series, cudf.Series]
75+
DataFrameType = Union[pd.DataFrame, cudf.DataFrame] # type: ignore
76+
SeriesType = Union[pd.Series, cudf.Series] # type: ignore
7777
else:
78-
DataFrameType = Union[pd.DataFrame]
79-
SeriesType = Union[pd.Series]
78+
DataFrameType = pd.DataFrame # type: ignore
79+
SeriesType = pd.Series # type: ignore
80+
8081

8182
# Define mapping between non-nullable,
8283
# and nullable types in Pandas

‎merlin/io/csv.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def to_ddf(self, columns=None, cpu=None):
6060
ddf = ddf[columns]
6161
return ddf
6262

63-
@property
63+
@property # type: ignore
6464
@functools.lru_cache(1)
6565
def _file_partition_map(self):
6666
ind = 0

‎merlin/io/parquet.py‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515
#
1616
import functools
17+
import io as py_io
1718
import itertools
1819
import logging
1920
import math
@@ -22,7 +23,6 @@
2223
import threading
2324
import warnings
2425
from collections import defaultdict
25-
from io import BytesIO
2626
from uuid import uuid4
2727

2828
from packaging.version import Version
@@ -332,12 +332,12 @@ def __init__(
332332

333333
assert self.row_groups_per_part > 0
334334

335-
@property
335+
@property # type: ignore
336336
@functools.lru_cache(1)
337337
def _path0(self):
338338
return next(self._dataset.get_fragments()).path
339339

340-
@property
340+
@property # type: ignore
341341
@functools.lru_cache(1)
342342
def _legacy_dataset(self):
343343
# TODO: Remove this after finding a way to avoid
@@ -355,7 +355,7 @@ def _legacy_dataset(self):
355355
dataset = pq.ParquetDataset(paths[0], filesystem=fs)
356356
return dataset
357357

358-
@property
358+
@property # type: ignore
359359
@functools.lru_cache(1)
360360
def _dataset(self):
361361
paths = self.stripped_paths
@@ -595,7 +595,7 @@ def validate_dataset(
595595
paths,
596596
out_dir=False,
597597
)
598-
with BytesIO() as myio:
598+
with py_io.BytesIO() as myio:
599599
myio.write(memoryview(metadata_bytes))
600600
myio.seek(0)
601601
metadata = pq.ParquetFile(myio).metadata
@@ -930,9 +930,7 @@ def _write_data(data_list, output_path, fs, fn):
930930
class BaseParquetWriter(ThreadedWriter):
931931
def __init__(self, out_dir, suffix=".parquet", **kwargs):
932932
super().__init__(out_dir, **kwargs)
933-
self.data_paths = []
934933
self.data_files = []
935-
self.data_writers = []
936934
self.data_bios = []
937935
self._lock = threading.RLock()
938936
self.pwriter = self._pwriter
@@ -968,7 +966,7 @@ def _append_writer(self, path, schema=None, add_args=None, add_kwargs=None):
968966
_kwargs = tlz.merge(self.pwriter_kwargs, add_kwargs or {})
969967

970968
if self.bytes_io:
971-
bio = BytesIO()
969+
bio = py_io.BytesIO()
972970
self.data_bios.append(bio)
973971
self.data_writers.append(self.pwriter(bio, *_args, **_kwargs))
974972
else:

‎merlin/io/writer.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ def __init__(
8989
self.num_out_files = num_out_files
9090
self.num_samples = [0] * self.num_out_files
9191

92-
self.data_paths = None
92+
self.data_paths = []
93+
self.data_writers = []
94+
9395
self.need_cal_col_names = True
9496
self.use_guid = use_guid
9597
self.bytes_io = bytes_io

‎merlin/schema/io/tensorflow_metadata.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
#
15+
import os
1516
import pathlib
1617
from typing import Union
1718

@@ -63,7 +64,7 @@ def from_json(cls, json: Union[str, bytes]) -> "TensorflowMetadata":
6364
return TensorflowMetadata(schema)
6465

6566
@classmethod
66-
def from_json_file(cls, path: str) -> "TensorflowMetadata":
67+
def from_json_file(cls, path: os.PathLike) -> "TensorflowMetadata":
6768
"""Create a TensorflowMetadata schema object from a JSON file
6869
6970
Parameters
@@ -103,7 +104,9 @@ def from_proto_text(cls, proto_text: str) -> "TensorflowMetadata":
103104
return TensorflowMetadata(schema)
104105

105106
@classmethod
106-
def from_proto_text_file(cls, path: str, file_name="schema.pbtxt") -> "TensorflowMetadata":
107+
def from_proto_text_file(
108+
cls, path: os.PathLike, file_name="schema.pbtxt"
109+
) -> "TensorflowMetadata":
107110
"""Create a TensorflowMetadata schema object from a Protobuf text file
108111
109112
Parameters
@@ -120,7 +123,7 @@ def from_proto_text_file(cls, path: str, file_name="schema.pbtxt") -> "Tensorflo
120123
121124
"""
122125
path = pathlib.Path(path) / file_name
123-
return cls.from_proto_text(_read_file(str(path)))
126+
return cls.from_proto_text(_read_file(path))
124127

125128
def to_proto_text(self) -> str:
126129
"""Convert this TensorflowMetadata schema object to a Proto text string
@@ -414,7 +417,7 @@ def _merlin_column(feature):
414417
return ColumnSchema(name, tags, properties, dtype, is_list, is_ragged=is_ragged)
415418

416419

417-
def _read_file(path: str):
420+
def _read_file(path: os.PathLike):
418421
# TODO: Should we be using fsspec here too?
419422
path = pathlib.Path(path)
420423
if path.is_file():

‎merlin/schema/schema.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class ColumnSchema:
3535

3636
name: Text
3737
tags: Optional[TagSet] = field(default_factory=TagSet)
38-
properties: Optional[Dict[str, any]] = field(default_factory=dict)
38+
properties: Optional[Dict] = field(default_factory=dict)
3939
dtype: Optional[object] = None
4040
is_list: bool = False
4141
is_ragged: bool = False

‎merlin/schema/tags.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# limitations under the License.
1515
#
1616
from enum import Enum
17-
from typing import List, Union
17+
from typing import List, Set, Union
1818

1919

2020
class Tags(Enum):
@@ -55,11 +55,12 @@ class TagSet:
5555
"""Collection that normalizes tags and prevents collisions between incompatible tags"""
5656

5757
def __init__(self, tags: List[Union[str, Tags]] = None):
58-
tags = tags or []
5958
if isinstance(tags, TagSet):
60-
tags = tags._tags
59+
tags = list(tags._tags)
60+
elif tags is None:
61+
tags = []
6162

62-
self._tags = self._normalize_tags(tags)
63+
self._tags: Set[Tags] = self._normalize_tags(tags)
6364

6465
collisions = self._detect_collisions(self._tags, self._tags)
6566
if collisions:
@@ -121,7 +122,7 @@ def _convert_to_tagset(self, tags):
121122

122123
return tags
123124

124-
def _normalize_tags(self, tags):
125+
def _normalize_tags(self, tags) -> Set[Tags]:
125126
return set(Tags[tag.upper()] if tag in Tags._value2member_map_ else tag for tag in tags)
126127

127128
def __repr__(self) -> str:

0 commit comments

Comments
 (0)