Debian Codegraph @

clevercsv/cparser_util.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Python utility functions that wrap the C parser.
5
6 """
7
8 import io
9
10 from typing import Any
11 from typing import Iterable
12 from typing import Iterator
13 from typing import List
14 from typing import Optional
15 from typing import Tuple
16 from typing import Union
17
18 from .cparser import Error as ParserError
19 from .cparser import Parser
20 from .dialect import SimpleDialect
21 from .exceptions import Error
22
23 _FIELD_SIZE_LIMIT: int = 128 * 1024
24
25
26 def field_size_limit(*args: Any, **kwargs: Any) -> int:
27 """Get/Set the limit to the field size.
28
29 This function is adapted from the one in the Python CSV module. See the
30 documentation there.
31 """
32 global _FIELD_SIZE_LIMIT
33 old_limit = _FIELD_SIZE_LIMIT
34 all_args = list(args) + list(kwargs.values())
35 if not 0 <= len(all_args) <= 1:
36 raise TypeError(
37 "field_size_limit expected at most 1 arguments, got %i"
38 % len(all_args)
39 )
40 if len(all_args) == 0:
41 return old_limit
42 limit = all_args[0]
43 if not isinstance(limit, int):
44 raise TypeError("limit must be an integer")
45 _FIELD_SIZE_LIMIT = int(limit)
46 return old_limit
47
48
49 def _parse_data(
50 data: Iterable[str],
51 delimiter: str,
52 quotechar: str,
53 escapechar: str,
54 strict: bool,
55 return_quoted: bool = False,
56 ) -> Iterator[Union[List[str], List[Tuple[str, bool]]]]:
57 parser = Parser(
58 data,
59 delimiter=delimiter,
60 quotechar=quotechar,
61 escapechar=escapechar,
62 field_limit=field_size_limit(),
63 strict=strict,
64 return_quoted=return_quoted,
65 )
66 try:
67 for row in parser:
68 yield row
69 except ParserError as e:
70 raise Error(str(e))
71
72
73 def parse_data(
74 data: Iterable[str],
75 dialect: Optional[SimpleDialect] = None,
76 delimiter: Optional[str] = None,
77 quotechar: Optional[str] = None,
78 escapechar: Optional[str] = None,
79 strict: Optional[bool] = None,
80 return_quoted: bool = False,
81 ) -> Iterator[Union[List[str], List[Tuple[str, bool]]]]:
82 """Parse the data given a dialect using the C parser
83
84 Parameters
85 ----------
86 data : iterable
87 The data of the CSV file as an iterable
88
89 dialect : SimpleDialect
90 The dialect to use for the parsing. If None, the dialect with each
91 component set to the empty string is used.
92
93 delimiter : str
94 The delimiter to use. If not None, overwrites the delimiter in the
95 dialect.
96
97 quotechar : str
98 The quote character to use. If not None, overwrites the quote character
99 in the dialect.
100
101 escapechar : str
102 The escape character to use. If not None, overwrites the escape
103 character in the dialect.
104
105 strict : bool
106 Enable strict mode or not. If not None, overwrites the strict mode set
107 in the dialect.
108
109 return_quoted : bool
110 For each cell, return a tuple "(field, is_quoted)" where the second
111 element indicates whether the cell was a quoted cell or not.
112
113 Yields
114 ------
115 rows : list
116 The rows of the file as a list of cells.
117
118 Raises
119 ------
120 Error : clevercsv.exceptions.Error
121 When an error occurs during parsing.
122
123 """
124 if dialect is None:
125 dialect = SimpleDialect("", "", "")
126
127 delimiter_ = delimiter if delimiter is not None else dialect.delimiter
128 quotechar_ = quotechar if quotechar is not None else dialect.quotechar
129 escapechar_ = escapechar if escapechar is not None else dialect.escapechar
130 strict_ = strict if strict is not None else dialect.strict
131
132 yield from _parse_data(
133 data,
134 delimiter_,
135 quotechar_,
136 escapechar_,
137 strict_,
138 return_quoted=return_quoted,
139 )
140
141
142 def parse_string(
143 data: str,
144 dialect: SimpleDialect,
145 return_quoted: bool = False,
146 ) -> Iterator[Union[List[str], List[Tuple[str, bool]]]]:
147 """Utility for when the CSV file is encoded as a single string"""
148 return parse_data(
149 iter(io.StringIO(data, newline="")),
150 dialect=dialect,
151 return_quoted=return_quoted,
152 )