Skip to content

Do not cut data at a random position when passing it to chardet - #36

Closed
M-Reimer wants to merge 1 commit into
kovidgoyal:masterfrom
M-Reimer:master
Closed

M-Reimer wants to merge 1 commit into
kovidgoyal:masterfrom
M-Reimer:master

Conversation

@M-Reimer

@M-Reimer M-Reimer commented Oct 26, 2026 •

Copy link
Copy Markdown

I'm currently doing some research about character detection and how other projects have solved it.

While doing so, I also stumbled across your project and I found that you pre-cut the data before passing it over for detection.
This should not be done for several reasons:

  • Character detection libraries have their own sequencing and process data until they are sure they successfully detected the charset.
  • Some charsets require multi-byte sequences to be detected. If you cut a sequence at a random place, it may happen that you "break apart" this sequence which throws off the detection.
  • Some text content may start with "like ASCII" characters and use unicode characters later in the content. If you only pass a sequence from the start, the unicode characters are not detected and the final decoding of the whole byte string fails with an unicode decode error.
  • Python passes the byte string "by reference" if it is not modified. By "pre-cutting", Python has to allocate new memory to store your temporary byte string just for detection.

This risks that a multibyte character sequence is cut in between which may throw off the detection
@kovidgoyal

Copy link
Copy Markdown
Owner

Detectin encoding from arbitrary long strings is too slow. Copying 50KB of data is a trivial cost, though if you really really want to avoid that usea memoryview assuming chardet supports it. And one broken multi byte sequence from 50KB of data is not going to break any decent detector.

@kovidgoyal kovidgoyal closed this Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants