Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions Lib/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,12 +280,16 @@ def _guess_quote_and_delimiter(self, data, delimiters):
"""
import re

# The body of a quoted field ends at the first quote which is
# not doubled, as it does for a reader. A lazy ".*?" scans to
# the end of the sample instead, from every start: quadratically.
body = r'(?:(?P=quote){2}|(?!(?P=quote)).)*+'
matches = []
for restr in (r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\r|\n)', # ,".*?"
r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\r|\n)'): # ".*?" (no delim, no space)
regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
for restr in (r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\'])%s(?P=quote)(?P=delim)', # ,"...",
r'(?:^|\n)(?P<quote>["\'])%s(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # "...",
r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\'])%s(?P=quote)(?:$|\r|\n)', # ,"..."
r'(?:^|\n)(?P<quote>["\'])%s(?P=quote)(?:$|\r|\n)'): # "..." (no delim, no space)
regexp = re.compile(restr % body, re.DOTALL | re.MULTILINE)
matches = regexp.findall(data)
if matches:
break
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -1564,6 +1564,14 @@ def test_zero_mode_tie_order_colon_first(self):
sniffer.sniff(sample)


def test_sniff_quoted_single_column(self):
# gh-98820: this sample used to take minutes.
sniffer = csv.Sniffer()
sample = '"abcdefghijklmnopqrstuvwxyz"\n' * 10000
with self.assertRaisesRegex(csv.Error, "Could not determine delimiter"):
sniffer.sniff(sample, delimiters=',:|\t')


class NUL:
def write(s, *args):
pass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix quadratic time in :meth:`csv.Sniffer.sniff` for a sample which contains
quoted fields, in particular for a single column of quoted fields.
Loading