4 ms·
Nitpick: Python strings are not "UTF-8"; they are abstract sequences of Unicode codepoints (and internally CPython stores UTF-32). However, UTF-8 is the default
by nerdponx 4y ago
Nitpick: Python strings are not "UTF-8"; they are abstract sequences of Unicode codepoints (and internally CPython stores UTF-32). However, UTF-8 is the default encoding for processing raw bytes received from the outside world and turning them into strings.
That said, I actually didn't realize that os.listdir() silently omits un-decodable entries, which I find mildly alarming. This behavior isn't mentioned in the docs (https://docs.python.org/3/library/os.html#os.listdir https://docs.python.org/3/library/os.html#os.listdir) and seems out-of-character for Python, which usually raises an exception by default if data cannot be decoded to text.
Are you sure that this is actually what happens with non-decodable filenames? Reading here (https://docs.python.org/3/glossary.html#term-filesystem-encoding-and-error-handler https://docs.python.org/3/glossary.html#term-filesystem-enco...) and here (https://docs.python.org/3/c-api/init_config.html#c.PyConfig.filesystem_errors https://docs.python.org/3/c-api/init_config.html#c.PyConfig....), it suggests that encoding errors should be handled by surrogate escapes by default on non-Windows systems.
- jefftk 4y agoI'm wrong: https://news.ycombinator.com/item?id=32471944 https://news.ycombinator.com/item?id=32471944 If it ever did that, it doesn't anymore.
- jefftk 4y agoFound some history: https://vstinner.github.io/python30-listdir-undecodable-filenames.html https://vstinner.github.io/python30-listdir-undecodable-file... Includes "Modify os.listdir(str) to ignore silently undecodable filenames, instead of returning them as bytes", but not later work where apparently this was changed to use surrogates.
- fabioz 4y agoJust as a note, the way that Python stores the items isn't always 4 bytes per char, it depends on the actual string contents. I think that https://rushter.com/blog/python-strings-and-memory/ https://rushter.com/blog/python-strings-and-memory/ is a nice reference on that.
- nerdponx 4y agoInteresting and good to know! CPython is really quite impressive with all of these little optimizations.