|
2 | 2 | import csv |
3 | 3 |
|
4 | 4 | from datetime import date, datetime |
5 | | -from typing import Union, Type, Optional, Sequence, Dict, Any, List |
| 5 | +from typing import Union, Type, Optional, Sequence, Dict, Any, List, Generic, TypeVar |
6 | 6 |
|
7 | 7 | import typing |
8 | 8 |
|
|
12 | 12 | from collections import Counter |
13 | 13 |
|
14 | 14 |
|
| 15 | +T = TypeVar("T") |
| 16 | + |
15 | 17 | def _verify_duplicate_header_items(header): |
16 | 18 | if header is not None and len(header) == 0: |
17 | 19 | return |
@@ -60,11 +62,11 @@ def get_args(t): |
60 | 62 | return tuple() |
61 | 63 |
|
62 | 64 |
|
63 | | -class DataclassReader: |
| 65 | +class DataclassReader(Generic[T]): |
64 | 66 | def __init__( |
65 | 67 | self, |
66 | 68 | f: Any, |
67 | | - cls: Type[object], |
| 69 | + cls: Type[T], |
68 | 70 | fieldnames: Optional[Sequence[str]] = None, |
69 | 71 | restkey: Optional[str] = None, |
70 | 72 | restval: Optional[Any] = None, |
@@ -198,7 +200,7 @@ def _parse_date_value(self, field, date_value, field_type): |
198 | 200 | else: |
199 | 201 | return datetime_obj |
200 | 202 |
|
201 | | - def _process_row(self, row): |
| 203 | + def _process_row(self, row) -> T: |
202 | 204 | values = dict() |
203 | 205 |
|
204 | 206 | for field in dataclasses.fields(self._cls): |
@@ -257,7 +259,7 @@ def _process_row(self, row): |
257 | 259 | values[field.name] = transformed_value |
258 | 260 | return self._cls(**values) |
259 | 261 |
|
260 | | - def __next__(self): |
| 262 | + def __next__(self) -> T: |
261 | 263 | row = next(self._reader) |
262 | 264 | return self._process_row(row) |
263 | 265 |
|
|
0 commit comments