Debian Codegraph @

clevercsv/dialect.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Definitions for the dialect object.
6
7 Author: Gertjan van den Burg
8
9 """
10
11 import csv
12 import functools
13 import json
14
15 from typing import Any
16 from typing import Dict
17 from typing import Optional
18 from typing import Tuple
19 from typing import Union
20
21 import _csv
22
23 excel = csv.excel
24 excel_tab = csv.excel_tab
25 unix_dialect = csv.unix_dialect
26
27
28 @functools.total_ordering
29 class SimpleDialect:
30 """
31 The simplified dialect object.
32
33 For the delimiter, quotechar, and escapechar the empty string means no
34 delimiter/quotechar/escapechar in the file. None is used to mark it
35 undefined.
36
37 Parameters
38 ----------
39 delimiter : str
40 The delimiter of the CSV file.
41
42 quotechar : str
43 The quotechar of the file.
44
45 escapechar : str
46 The escapechar of the file.
47
48 strict : bool
49 Whether strict parsing should be enforced. Same as in the csv module.
50
51 """
52
53 def __init__(
54 self,
55 delimiter: Optional[str],
56 quotechar: Optional[str],
57 escapechar: Optional[str],
58 strict: bool = False,
59 ):
60 self.delimiter = delimiter
61 self.quotechar = quotechar
62 self.escapechar = escapechar
63 self.strict = strict
64
65 def validate(self) -> None:
66 if self.delimiter is None or len(self.delimiter) > 1:
67 raise ValueError(
68 "Delimiter should be zero or one characters, got: %r"
69 % self.delimiter
70 )
71 if self.quotechar is None or len(self.quotechar) > 1:
72 raise ValueError(
73 "Quotechar should be zero or one characters, got: %r"
74 % self.quotechar
75 )
76 if self.escapechar is None or len(self.escapechar) > 1:
77 raise ValueError(
78 "Escapechar should be zero or one characters, got: %r"
79 % self.escapechar
80 )
81 if self.strict not in set([False, True]):
82 raise ValueError(
83 "Strict should be True or False, got: %r" % self.strict
84 )
85
86 @classmethod
87 def from_dict(
88 cls: type["SimpleDialect"], d: Dict[str, Any]
89 ) -> "SimpleDialect":
90 dialect = cls(
91 d["delimiter"], d["quotechar"], d["escapechar"], strict=d["strict"]
92 )
93 return dialect
94
95 @classmethod
96 def from_csv_dialect(
97 cls: type["SimpleDialect"],
98 d: Union[_csv.Dialect, csv.Dialect],
99 ) -> "SimpleDialect":
100 delimiter = "" if d.delimiter is None else d.delimiter
101 quotechar = "" if d.quoting == csv.QUOTE_NONE else d.quotechar
102 escapechar = "" if d.escapechar is None else d.escapechar
103 return cls(delimiter, quotechar, escapechar, strict=d.strict)
104
105 def to_csv_dialect(self) -> csv.Dialect:
106 class dialect(csv.Dialect):
107 assert self.delimiter is not None
108 delimiter = self.delimiter
109 quotechar = '"' if self.quotechar == "" else self.quotechar
110 escapechar = None if self.escapechar == "" else self.escapechar
111 doublequote = True
112 quoting = (
113 csv.QUOTE_NONE if self.quotechar == "" else csv.QUOTE_MINIMAL
114 )
115 skipinitialspace = False
116 # TODO: We need to set this because it can't be None anymore in
117 # recent versions of Python
118 lineterminator = "\n"
119
120 return dialect()
121
122 def to_dict(self) -> Dict[str, Union[str, bool, None]]:
123 self.validate()
124 d = dict(
125 delimiter=self.delimiter,
126 quotechar=self.quotechar,
127 escapechar=self.escapechar,
128 strict=self.strict,
129 )
130 return d
131
132 def serialize(self) -> str:
133 """Serialize dialect to a JSON object"""
134 return json.dumps(self.to_dict())
135
136 @classmethod
137 def deserialize(cls: type["SimpleDialect"], obj: str) -> "SimpleDialect":
138 """Deserialize dialect from a JSON object"""
139 return cls.from_dict(json.loads(obj))
140
141 def __repr__(self) -> str:
142 return "SimpleDialect(%r, %r, %r)" % (
143 self.delimiter,
144 self.quotechar,
145 self.escapechar,
146 )
147
148 def __key(
149 self,
150 ) -> Tuple[Optional[str], Optional[str], Optional[str], bool]:
151 return (self.delimiter, self.quotechar, self.escapechar, self.strict)
152
153 def __hash__(self) -> int:
154 return hash(self.__key())
155
156 def __eq__(self, other: Any) -> bool:
157 if not isinstance(other, SimpleDialect):
158 return False
159 return self.__key() == other.__key()
160
161 def __lt__(self, other: Any) -> bool:
162 # This provides a partial order on dialect objects with the goal of
163 # speeding up the consistency measure.
164 if not isinstance(other, SimpleDialect):
165 return False
166 if self.delimiter == "," and not other.delimiter == ",":
167 return True
168 elif other.delimiter == "," and not self.delimiter == ",":
169 return False
170 if self.delimiter == ";" and not other.delimiter == ";":
171 return True
172 elif other.delimiter == ";" and not self.delimiter == ";":
173 return False
174 return self.__key() < other.__key()