Scrapy, a fast high-level web crawling & scraping framework for Python.
Optimize binary_is_text control character scan (#8362)
codspeed[bot]1b4b7946e36f
diff --git a/scrapy/utils/python.py b/scrapy/utils/python.pyindex 3864814fc..42cc46dcb 100644--- a/scrapy/utils/python.py+++ b/scrapy/utils/python.py@@ -168,6 +168,9 @@ def memoizemethod_noargs(_BINARYCHARS = {i for i in range(32) if chr(i).encode() not in {b"\0", b"\t", b"\n", b"\r"}}+# Matching the characters above with a compiled pattern lets binary_is_text()+# scan the data in C, instead of iterating over every byte in Python.+_BINARYCHARS_RE = re.compile(b"[" + re.escape(bytes(sorted(_BINARYCHARS))) + b"]")def binary_is_text(data: bytes) -> bool:@@ -176,7 +179,7 @@ def binary_is_text(data: bytes) -> bool:"""if not isinstance(data, bytes):raise TypeError(f"data must be bytes, got '{type(data).__name__}'")- return all(c not in _BINARYCHARS for c in data)+ return _BINARYCHARS_RE.search(data) is None# PEP 649 (Python 3.14+) made annotation evaluation lazy, so inspect.signature()