Debian Codegraph @

clevercsv/dict_read_write.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 DictReader and DictWriter.
5
6 This code is entirely copied from the Python csv module. The only exception is
7 that it uses the `reader` and `writer` classes from our package.
8
9 Author: Gertjan van den Burg
10
11 """
12
13 from __future__ import annotations
14
15 import warnings
16
17 from collections import OrderedDict
18 from collections.abc import Collection
19
20 from typing import TYPE_CHECKING
21 from typing import Any
22 from typing import Generic
23 from typing import Iterable
24 from typing import Iterator
25 from typing import Literal
26 from typing import Mapping
27 from typing import Optional
28 from typing import Sequence
29 from typing import TypeVar
30 from typing import Union
31 from typing import cast
32
33 from clevercsv.read import reader
34 from clevercsv.write import writer
35
36 if TYPE_CHECKING:
37 from clevercsv._types import SupportsWrite
38 from clevercsv._types import _DialectLike
39 from clevercsv._types import _DictReadMapping
40
41 _T = TypeVar("_T")
42
43
44 class DictReader(
45 Generic[_T], Iterator["_DictReadMapping[Union[_T, Any], Union[str, Any]]"]
46 ):
47 def __init__(
48 self,
49 f: Iterable[str],
50 fieldnames: Optional[Sequence[_T]] = None,
51 restkey: Optional[str] = None,
52 restval: Optional[str] = None,
53 dialect: "_DialectLike" = "excel",
54 *args: Any,
55 **kwds: Any,
56 ) -> None:
57 self._fieldnames = fieldnames
58 self.restkey = restkey
59 self.restval = restval
60 self.reader: reader = reader(f, dialect, *args, **kwds)
61 self.dialect = dialect
62 self.line_num = 0
63
64 def __iter__(self) -> "DictReader[_T]":
65 return self
66
67 @property
68 def fieldnames(self) -> Sequence[_T]:
69 if self._fieldnames is None:
70 try:
71 fieldnames = next(self.reader)
72 self._fieldnames = [cast(_T, f) for f in fieldnames]
73 except StopIteration:
74 pass
75
76 assert self._fieldnames is not None
77
78 # Note: this was added because I don't think it's expected that Python
79 # simply drops information if there are duplicate headers. There is
80 # discussion on this issue in the Python bug tracker here:
81 # https://bugs.python.org/issue17537 (see linked thread therein). A
82 # warning is easy enough to suppress and should ensure that the user
83 # is at least aware of this behavior.
84 if not len(self._fieldnames) == len(set(self._fieldnames)):
85 warnings.warn(
86 "fieldnames are not unique, some columns will be dropped."
87 )
88
89 self.line_num = self.reader.line_num
90 return self._fieldnames
91
92 @fieldnames.setter
93 def fieldnames(self, value: Sequence[_T]) -> None:
94 self._fieldnames = value
95
96 def __next__(self) -> "_DictReadMapping[Union[_T, Any], Union[str, Any]]":
97 if self.line_num == 0:
98 self.fieldnames
99 row = next(self.reader)
100 self.line_num = self.reader.line_num
101
102 while row == []:
103 row = next(self.reader)
104
105 d: _DictReadMapping = OrderedDict(zip(self.fieldnames, row))
106 lf = len(self.fieldnames)
107 lr = len(row)
108 if lf < lr:
109 d[self.restkey] = row[lf:]
110 elif lf > lr:
111 for key in self.fieldnames[lr:]:
112 d[key] = self.restval
113 return d
114
115
116 class DictWriter(Generic[_T]):
117 def __init__(
118 self,
119 f: SupportsWrite[str],
120 fieldnames: Collection[_T],
121 restval: Optional[Any] = "",
122 extrasaction: Literal["raise", "ignore"] = "raise",
123 dialect: "_DialectLike" = "excel",
124 *args: Any,
125 **kwds: Any,
126 ):
127 self.fieldnames = fieldnames
128 self.restval = restval
129 if extrasaction.lower() not in ("raise", "ignore"):
130 raise ValueError(
131 "extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction
132 )
133 self.extrasaction = extrasaction
134 self.writer = writer(f, dialect, *args, **kwds)
135
136 def writeheader(self) -> Any:
137 header = dict(zip(self.fieldnames, self.fieldnames))
138 return self.writerow(header)
139
140 def _dict_to_list(self, rowdict: Mapping[_T, Any]) -> Iterator[Any]:
141 if self.extrasaction == "raise":
142 wrong_fields = rowdict.keys() - self.fieldnames
143 if wrong_fields:
144 raise ValueError(
145 "dict contains fields not in fieldnames: "
146 + ", ".join([repr(x) for x in wrong_fields])
147 )
148 return (rowdict.get(key, self.restval) for key in self.fieldnames)
149
150 def writerow(self, rowdict: Mapping[_T, Any]) -> Any:
151 return self.writer.writerow(self._dict_to_list(rowdict))
152
153 def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None:
154 return self.writer.writerows(map(self._dict_to_list, rowdicts))