Skip to content

Commit 85ecf15

Browse files
authored
Merge pull request #2 from tekktrik/feature/add-typing
Minor updates/fixes
2 parents 096a223 + ce2896b commit 85ecf15

File tree

1 file changed

+33
-36
lines changed

1 file changed

+33
-36
lines changed

circuitpython_csv.py

Lines changed: 33 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
import re
3232

3333
try:
34-
from typing import List, Optional, Any, Dict
34+
from typing import List, Optional, Any, Dict, Iterable, Sequence
3535
import io
3636
except ImportError:
3737
pass
@@ -42,25 +42,23 @@ class reader: # pylint: disable=invalid-name
4242
4343
:param csvfile: The open file to read from
4444
:param delimiter: The CSV delimiter, default is comma (,)
45-
:param quotechar: The CSV quote character for encapsulating special characters \
46-
including the delimiter, default is double quotation mark (")
45+
:param quotechar: The CSV quote character for encapsulating special characters
46+
including the delimiter, default is double quotation mark (")
4747
"""
4848

4949
def __init__(
5050
self, csvfile: io.TextIOWrapper, delimiter: str = ",", quotechar: str = '"'
51-
):
51+
) -> None:
5252

5353
self.file_interator = csvfile
5454
self.delimiter = delimiter
5555
self.quotechar = quotechar
56-
self._re_exp = (
57-
"(\\" + quotechar + ".+?\\" + quotechar + "),|([^" + delimiter + "]+)"
58-
)
56+
self._re_exp = "(\\{0}.+?\\{0}),|([^{1}]+)".format(quotechar, delimiter)
5957

60-
def __iter__(self):
58+
def __iter__(self) -> "reader":
6159
return self
6260

63-
def __next__(self):
61+
def __next__(self) -> List[str]:
6462
csv_value_list = []
6563
row_string = self.file_interator.__next__()
6664

@@ -103,20 +101,20 @@ class writer: # pylint: disable=invalid-name
103101
104102
:param csvfile: The open CSVfile to write to
105103
:param delimiter: The CSV delimiter, default is comma (,)
106-
:param quotechar: The CSV quote character for encapsulating special characters \
107-
including the delimiter, default is double quotation mark (")
104+
:param quotechar: The CSV quote character for encapsulating special characters
105+
including the delimiter, default is double quotation mark (")
108106
"""
109107

110108
def __init__(
111109
self, csvfile: io.TextIOWrapper, delimiter: str = ",", quoterchar: str = '"'
112-
):
110+
) -> None:
113111

114112
self.file_iterator = csvfile
115113
self.delimiter = delimiter
116114
self.quotechar = quoterchar
117115
self.newlinechar = "\r\n"
118116

119-
def writerow(self, seq: List[str]):
117+
def writerow(self, seq: List[str]) -> None:
120118
"""Write a row to the CSV file
121119
122120
:param seq: The list of values to write
@@ -130,15 +128,15 @@ def writerow(self, seq: List[str]):
130128
parsed_str = (self.delimiter).join(quoted_seq)
131129
self.file_iterator.write(parsed_str + self.newlinechar)
132130

133-
def writerows(self, rows: iter):
131+
def writerows(self, rows: iter) -> None:
134132
"""Write multiple rows to the CSV file
135133
136134
:param rows: An iterable item that yields multiple rows to write (e.g., list)
137135
"""
138136
for row in rows:
139137
self.writerow(row)
140138

141-
def _apply_quotes(self, entry):
139+
def _apply_quotes(self, entry: str) -> str:
142140
"""Apply the quote character to entries as necessary
143141
144142
:param entry: The entry to add the quote charcter to, if needed
@@ -157,12 +155,12 @@ class DictReader:
157155
it also accepts the delimiter and quotechar keywords
158156
159157
:param f: The open file to read from
160-
:param fieldnames: The fieldnames for each of the columns, if none is given, \
161-
it will default to the whatever is in the first row of the CSV file
162-
:param restkey: A key name for values that have no key (row is larger than \
163-
the length of fieldnames), default is None
164-
:param restval: A default value for keys that have no values (row is small \
165-
than the length of fieldnames, default is None
158+
:param fieldnames: The fieldnames for each of the columns, if none is given,
159+
it will default to the whatever is in the first row of the CSV file
160+
:param restkey: A key name for values that have no key (row is larger than
161+
the length of fieldnames), default is None
162+
:param restval: A default value for keys that have no values (row is small
163+
than the length of fieldnames, default is None
166164
"""
167165

168166
def __init__(
@@ -172,18 +170,18 @@ def __init__(
172170
restkey: Optional[str] = None,
173171
restval: Optional[Any] = None,
174172
**kwargs
175-
):
173+
) -> None:
176174

177175
self.fieldnames = fieldnames
178176
self.restkey = restkey
179177
self.restval = restval
180178
self.reader = reader(f, **kwargs)
181179
self.line_num = 0
182180

183-
def __iter__(self):
181+
def __iter__(self) -> "DictReader":
184182
return self
185183

186-
def __next__(self):
184+
def __next__(self) -> List[str]:
187185
if self.line_num == 0:
188186
if self.fieldnames is None:
189187
self.fieldnames = next(self.reader)
@@ -209,9 +207,9 @@ class DictWriter:
209207
:param f: The open file to write to
210208
:param fieldnames: The fieldnames for each of the comlumns
211209
:param restval: A default value for keys that have no values
212-
:extrasaction: The action to perform if a key is encountered when parsing the dict that is \
213-
not included in the fieldnames parameter, either "raise" or "ignore". Ignore raises a \
214-
ValueError, and "ignore" simply ignore that key/value pair. Default behavior is "raise"
210+
:param extrasaction: The action to perform if a key is encountered when parsing the dict that is
211+
not included in the fieldnames parameter, either "raise" or "ignore". Ignore raises a
212+
ValueError, and "ignore" simply ignore that key/value pair. Default behavior is "raise"
215213
"""
216214

217215
def __init__(
@@ -221,7 +219,7 @@ def __init__(
221219
restval: str = "",
222220
extrasaction: str = "raise",
223221
**kwargs
224-
):
222+
) -> None:
225223
self.fieldnames = fieldnames # list of keys for the dict
226224
self.restval = restval # for writing short dicts
227225
if extrasaction.lower() not in ("raise", "ignore"):
@@ -231,12 +229,11 @@ def __init__(
231229
self.extrasaction = extrasaction
232230
self.writer = writer(f, **kwargs)
233231

234-
def writeheader(self):
232+
def writeheader(self) -> None:
235233
"""Writes the header row to the CSV file"""
236-
header = dict(zip(self.fieldnames, self.fieldnames))
237-
return self.writerow(header)
234+
self.writerow(dict(zip(self.fieldnames, self.fieldnames)))
238235

239-
def _dict_to_list(self, rowdict: Dict):
236+
def _dict_to_list(self, rowdict: Dict[str, Any]) -> Sequence[Any]:
240237
if self.extrasaction == "raise":
241238
wrong_fields = []
242239
for field in rowdict.keys():
@@ -249,15 +246,15 @@ def _dict_to_list(self, rowdict: Dict):
249246
)
250247
return (rowdict.get(key, self.restval) for key in self.fieldnames)
251248

252-
def writerow(self, rowdict: Dict):
249+
def writerow(self, rowdict: Dict[str, Any]) -> None:
253250
"""Writes a row to the CSV file
254251
255-
:param rowdict: The row to write as a dict, with keys of the DictWriter's \
256-
fieldnames parameter
252+
:param rowdict: The row to write as a dict, with keys of the DictWriter's
253+
fieldnames parameter
257254
"""
258255
return self.writer.writerow(self._dict_to_list(rowdict))
259256

260-
def writerows(self, rowdicts: iter):
257+
def writerows(self, rowdicts: Iterable[Any]) -> None:
261258
"""Writes multiple rows to the CSV files
262259
263260
:param rowdicts: An iterable item that yields multiple rows to write

0 commit comments

Comments
 (0)