|
|
Log in / Subscribe / Register

bytes vs. characters

bytes vs. characters

Posted Apr 15, 2015 15:21 UTC (Wed) by david.a.wheeler (subscriber, #72896)
In reply to: Report from the Python Language Summit by nix
Parent article: Report from the Python Language Summit

When you can be certain that all your input is perfectly formatted, the Python 3 string model is a good one. But the world isn't perfect. In particular, data sources routinely lie about their encoding, and Python 3 interferes with handling the real world instead of helping with it. For example, often there is no single encoding; many sources are a mishmash of UTF-8 and Windows-1252 and maybe some other stuff in a single file. What, exactly, is the encoding format of stdin? The answer is: there isn't one. What's the encoding format of filenames on Linux and Unix? There isn't one (they hacked around filenames, but failed to hack around ALL data sources, even though they all have this problem).

The "Unicode dammit" library helps. A little. But I find myself unable to find a reason to use Python 3, and I can find a long list of reasons to use Python 2 or some other language instead. I think I am not alone.


to post comments

bytes vs. characters

Posted Apr 15, 2015 18:22 UTC (Wed) by njs (subscriber, #40338) [Link]

> In particular, data sources routinely lie about their encoding, and Python 3 interferes with handling the real world instead of helping with it.

I'm curious if you could elaborate on what interference you're thinking of? I don't have a dog in the fight or anything, but my experience with py3 has been pretty pleasant so far, and I don't see off the top of my head how py3 could do worse than py2 in this case. It seems like at worse you would end writing the same code in both cases to treat the data as bytes, try different encodings or whatever you want, with the main difference that in py3 at least you don't have to deal with random functions deciding to help out by spontaneously encoding/decoding with some random codec? Or depending on what you're doing, surrogate-escape could be pretty useful too, and that's a py3 feature.

bytes vs. characters

Posted Apr 15, 2015 18:35 UTC (Wed) by HelloWorld (guest, #56129) [Link] (2 responses)

> But the world isn't perfect. In particular, data sources routinely lie about their encoding, and Python 3 interferes with handling the real world instead of helping with it.
The world is a messy place because we make it one. It's the idiotic “be liberal in what you accept” doctrine that led us here, and the only way out is to not create more crap that tries to cope with bad input in “helpful” ways rather than simply rejecting bad input.

bytes vs. characters

Posted Apr 15, 2015 21:28 UTC (Wed) by tpo (subscriber, #25713) [Link] (1 responses)

> The world is a messy place because we make it one. It's the idiotic “be liberal in what you accept” doctrine that led us here, and the only way out is to not create more crap that tries to cope with bad input in “helpful” ways rather than simply rejecting bad input.

I think "Truth" and "right" are attributes of the powerful. Whereas "be liberal in what you accept" is an expression of humility, of the wish to serve.

I can see the point of standing up for a cause. But probably the cause must not be self serving in order to legitimize the use of the force of refusal.

Maybe.

Remember what consequences "being right" had during the browser wars? Or how "being right" is constructing walled gardens today?

bytes vs. characters

Posted Apr 16, 2015 13:22 UTC (Thu) by smitty_one_each (subscriber, #28989) [Link]

> "be liberal in what you accept" is an expression of humility, of the wish to serve.

Excess rigidity is the key to maintaining a negligible user base.

bytes vs. characters

Posted Apr 16, 2015 21:33 UTC (Thu) by zyga (subscriber, #81533) [Link] (12 responses)

If you have mixed encoding just frelling use BYTES as that's what you are reading anyway. Bytes. Use bytes and be happy.

Don't say python3 is not practical for real world. It's like complaining that python has a int type and string type and you must use this confusing concept of using the right one at the right time while perl is so much better because it doesn't put this confusing non-real-life problem in front of you. That is totally missing the point.

People that stay stuck in python2 due to migration complexity are not the problem. They will eventually move. People that think python2 model of binary soup is somewhat superior or that you cannot achieve that in python3 need to get a clue.

bytes vs. characters

Posted Apr 16, 2015 22:36 UTC (Thu) by Cyberax (✭ supporter ✭, #52523) [Link] (11 responses)

> If you have mixed encoding just frelling use BYTES as that's what you are reading anyway. Bytes. Use bytes and be happy.
Except that you can't do it.

For example, JSON decoder in Python3 _insists_ on decoding strings as strings. Even if they have invalid UTF-8 data. It's bad, but such services do exist out there and sometimes you have to work with them.

Ditto for HTTP headers.

bytes vs. characters

Posted Apr 16, 2015 23:15 UTC (Thu) by dbaker (guest, #89236) [Link] (1 responses)

> For example, JSON decoder in Python3 _insists_ on decoding strings as strings. Even if they have invalid UTF-8 data. It's bad, but such services do exist out there and sometimes you have to work with them.

Because the JSON spec requires that strings must be unicode?

Can't you just write a custom object_hook function to pass to the decoder to solve your problem?

bytes vs. characters

Posted Apr 16, 2015 23:19 UTC (Thu) by Cyberax (✭ supporter ✭, #52523) [Link]

> Because the JSON spec requires that strings must be unicode?
Yes, but the reality outside is a little bit different.

> Can't you just write a custom object_hook function to pass to the decoder to solve your problem?
No, 'encoder' parameter is ignored in json.loads and everything else already gets decoded strings.

We simply switched to a third-party library instead.

bytes vs. characters

Posted Apr 17, 2015 7:15 UTC (Fri) by zyga (subscriber, #81533) [Link] (1 responses)

You can decode("UTF-8", "ignore") or something else to "coerce" it to some form of text though I really do value the sanity of that. Just fix your data sources. Even if you use some 3rd party library it's not going to make any of that "json"-like thing work with other libraries (I assume that other customers/APIs need to read it).

HTTP headers are a perfect example of binary data. Handling them as unicode text is broken IMHO. You can just use byte processing for everything there and Python 3.4, AFAIR, fixed some last gripes about lack of formatting support for edge cases like that.

bytes vs. characters

Posted Apr 17, 2015 7:22 UTC (Fri) by Cyberax (✭ supporter ✭, #52523) [Link]

> You can decode("UTF-8", "ignore") or something else to "coerce" it to some form of text though I really do value the sanity of that.
I think it will still be broken. There's a workaround that simply stores binary bytes in the lower byte of UCS-4 codepoints and it sorta works.

I'd love to fix these data sources, but they're out of my control. The vendor knows about it and they plan to base64 binary data in the future, but for now I have to work with what I have.

> You can just use byte processing for everything there and Python 3.4
Not exactly. Most of the built-in library can be used with byte sequences, but third-party libraries are often too careless.

I've fixed tons of code like this:

>def blah(p):
> if fail_to_do_something(p):
> raise SomeException(u"Failed to frobnicate %s!" % p)

It mostly works as is, but occasionally it doesn't.

bytes vs. characters

Posted Apr 17, 2015 14:35 UTC (Fri) by intgr (subscriber, #39733) [Link] (6 responses)

How is it a problem in Python that it insists on data to conform to a specification?

How do you think it should behave? Always return bytes? No, JSON specifies Unicode. Try Unicode first but fall back to bytes? No, that seems like it would be very surprising behavior and cause more bugs than it solves. AFAICT the alternatives are far worse.

The situation you're in is *caused* by implementations being too lenient and accepting junk as input, which is why the vendor has not noticed this issue before.

bytes vs. characters

Posted Apr 18, 2015 11:03 UTC (Sat) by mathstuf (subscriber, #69389) [Link] (5 responses)

So how do you put raw bytes into JSON then? How do you reasonably deal with people putting Latin-1 into comments on a website accessible via an API using JSON? Do you use an array of codepoints? Bytes? Personally, I like Python 2's json module which gives you a unicode object for UTF-8 and str for anything else (or pure ASCII). The problems there, however, come from other places such as subprocess.Popen.communicate choking on non-ASCII (so unicode object need encoded, but Latin-1 needed casted to bytes…which is the same as str, but still required for some reason), unicode strings can't be formatted with other unicode objects, but str can be (WTF logic is that?), and other pitfalls (of course, hidden until runtime, lucky me). It would be nice to move to Python 3 which seems like it fixes these problems, but this makes it sound like they just moved the ball around in some kind of shell game.

bytes vs. characters

Posted Apr 20, 2015 7:59 UTC (Mon) by zyga (subscriber, #81533) [Link] (4 responses)

You don't. There's no specification for putting random bytes in json.

At this time you just generate a stream of bytes (not python bytes, just bytes) that has some meaning that is only sensible to you and whoever consumes your byte stream. It's not json.

bytes vs. characters

Posted Apr 20, 2015 11:43 UTC (Mon) by Jonno (guest, #49613) [Link] (3 responses)

> You don't. There's no specification for putting random bytes in json.
Actually there is, it is called an "array of numbers", ie [ 97, 114, 114, 97, 121, 32, 111, 102, 32, 110, 117, 109, 98, 101, 114, 115, 0 ]

bytes vs. characters

Posted Apr 20, 2015 12:21 UTC (Mon) by bcopeland (subscriber, #51750) [Link]

For those, like me, who have a defect where they cannot resist converting ascii-valued hex or decimal numbers into their chr() equivalent, it all checks out.

bytes vs. characters

Posted Apr 20, 2015 13:19 UTC (Mon) by mathstuf (subscriber, #69389) [Link] (1 responses)

The problem is that "no" implementations do this :( . Ruby's libraries (or at least whatever GitLab uses) will happily make non-utf-8 strings in the JSON it exports. And Python2 will happily import it as a str object. There is *lots* of code that will need changing for stricter parsers/generators.

bytes vs. characters

Posted Apr 21, 2015 4:12 UTC (Tue) by lsl (subscriber, #86508) [Link]

Go's JSON package does use those number arrays when appropriate.

bytes vs. characters

Posted Apr 17, 2015 18:27 UTC (Fri) by marcH (subscriber, #57642) [Link] (19 responses)

> For example, often there is no single encoding; many sources are a mishmash of UTF-8 and Windows-1252 and maybe some other stuff in a single file.

"Many"... how many? Sure, it happens every time I throw the random cr*p stored on my hard drive at a quick and dirty script I just hacked together. I think it's a small price to pay for type safety whenever you and I write proper, reliable software.

If you have a source with an hopelessly entangled mix of UTF-8 and Windows-1252, and had the freedom to re-design Python3 (or whatever else), what sensible could you possibly do with it *anyway*? Genuine question.

bytes vs. characters

Posted Apr 23, 2015 15:27 UTC (Thu) by lopgok (guest, #43164) [Link] (18 responses)

I would like a simple way in python 3 to be able to read the names of all the files in a directory. In python 3, it skips over some files which I suspect are not in the current codespace. In python 2, it just reads the names of all of the files.

I understand it is problematic to do string processing on oddly constructed strings, but it is mission critical for me to be able to see all the files in a directory. If an exception was raised it would really suck, but it would suck less than silently skipping file names that it didn't understand.

That is the reason I have not migrated all of my development to python 3.

bytes vs. characters

Posted Apr 23, 2015 17:00 UTC (Thu) by cesarb (subscriber, #6266) [Link] (4 responses)

> I would like a simple way in python 3 to be able to read the names of all the files in a directory. In python 3, it skips over some files which I suspect are not in the current codespace. In python 2, it just reads the names of all of the files.

I just tested here, and the python3 in this machine returns all filenames in os.listdir('.'), even the one I created with an invalid UTF-8 encoding.

Skipping over some files was true in Python 3.0 (https://docs.python.org/3/whatsnew/3.0.html#text-vs-data-...):

"Note that when os.listdir() returns a list of strings, filenames that cannot be decoded properly are omitted rather than raising UnicodeError."

(The same paragraph mentions that you could still use os.listdir(b'.') to get all filenames as bytes, so even with Python 3.0 you already had a way to read the name of all the files.)

But that was probably changed in Python 3.1, when PEP 383 (https://www.python.org/dev/peps/pep-0383/) was implemented, since with it there are no "filenames that cannot be decoded properly".

bytes vs. characters

Posted Apr 23, 2015 22:09 UTC (Thu) by lopgok (guest, #43164) [Link] (3 responses)

It is still broken with python 3 when I tested it about 2 or 3 months ago. It was either python 3.3 or python 3.4

I have a directory which is read just fine with python 2.7, but skips files with python 3.

bytes vs. characters

Posted Apr 24, 2015 11:44 UTC (Fri) by cesarb (subscriber, #6266) [Link] (2 responses)

Does it still skip files if you use the "bytes" interface (os.listdir(b'.'))?

I just took a quick look at the current Python source code for os.listdir (https://hg.python.org/cpython/file/151cab576cab/Modules/p...), and it only has code to skip the "." and ".." entries, as it's documented to do. In both the "str" and the "bytes" case, it adds every entry other than these two. For it to skip anything else on os.listdir, readdir() from glibc has to be skipping it, and it should affect more than just Python.

Or is the problem with something other than os.listdir?

bytes vs. characters

Posted Apr 24, 2015 14:18 UTC (Fri) by lopgok (guest, #43164) [Link] (1 responses)

It is os.listdir. I have not tried accessing it in binary yet.

I do find it odd that the OS can list the file and I can manipulate the file name on the command line, but because it has some odd characters in it, python silently skips over it.

bytes vs. characters

Posted May 9, 2015 21:34 UTC (Sat) by nix (subscriber, #2304) [Link]

Well, if you want to read something no matter what its encoding, you use bytes mode. That's what bytes mode is *for*. Python 3 is really very consistent here (unlike Python 2, for which you had to guess and hope.)

bytes vs. characters

Posted Apr 23, 2015 17:07 UTC (Thu) by marcH (subscriber, #57642) [Link] (12 responses)

> In python 3, it skips over some files which I suspect are not in the current codespace [...] but it is mission critical for me to be able to see all the files in a directory.

"Mission-critical" relying on filename garbage, mmm.... really? What kind of mission?

bytes vs. characters

Posted Apr 23, 2015 18:03 UTC (Thu) by zlynx (guest, #2285) [Link]

Silent failure is always a STUPID idea.

If Python3 really is silently ignoring invalid filenames then that should be marked as a critical flaw.

The real world is not a perfect place with perfectly encoded strings.

bytes vs. characters

Posted Apr 23, 2015 20:33 UTC (Thu) by lsl (subscriber, #86508) [Link] (6 responses)

Why would they be garbage?

bytes vs. characters

Posted Apr 23, 2015 20:47 UTC (Thu) by marcH (subscriber, #57642) [Link] (5 responses)

> Why would they be garbage?

How else is any invalid encoding displayed?

bytes vs. characters

Posted Apr 23, 2015 22:07 UTC (Thu) by dlang (guest, #313) [Link] (1 responses)

they are only invalid if you decide ahead of time that they are supposed to be UTF8 strings.

the spec allows them to be a string of bytes (excluding null and /), no encoding is required.

bytes vs. characters

Posted Apr 23, 2015 22:30 UTC (Thu) by marcH (subscriber, #57642) [Link]

> they are only invalid if you decide ahead of time that they are supposed to be UTF8 strings.

They are invalid if you decide that they are supposed to be in some encoding and some filename uses any *other* encoding. Then garbage gets displayed: for real.

https://en.wikipedia.org/wiki/Mojibake (search page for "garbage")

It's less rare with removable media or ID3
https://en.wikipedia.org/wiki/ID3 (search page for "mojibake")

> the spec allows them to be a string of bytes (excluding null and /), no encoding is required.

As far as filenames are concerned, you meant: *the lack of* a spec.

http://www.dwheeler.com/essays/fixing-unix-linux-filename... (search page for... "garbage")

> no encoding is required.

Which command do you typically use instead of "ls"? hexdump?

bytes vs. characters

Posted Apr 24, 2015 6:57 UTC (Fri) by mbunkus (subscriber, #87248) [Link] (2 responses)

It's not about the display of broken information. That's the easy part.

But a reliable tool, especially one running on filesystems where nearly everything goes (including newlines in them and having no discernible encoding at all), should be able to handle such files, too. This goes double for tools where the developer doesn't control the input. Backup software is the prime example.

How often such files happen? You'd be surprised… Email clients are still broken and annotate file names with the wrong character set resulting in broken file names when saving. ZIP files don't have any encoding information at all, so unpacking one with a file name containing non-ASCII characters often results in ISO encoded file names on my UTF-8 system. And so on.

Therefore treating file names as anything else than a sequence of bytes is, in general, a really bad idea. Only force encodings in places where you need that encoding; displaying the file name being the prime example. If you store it in a database use binary column formats (or if you must use hex then use some kind of escaping mechanism like URL encoding an UTF-8 representation). UTF-8 representations have their own problems regarding file names, think of normalization forms and the fun you're having with Macs and non-Macs.

Treating file names correctly is hard enough. Forcing them into any kind of encoding only makes it worse.

bytes vs. characters

Posted Apr 24, 2015 17:22 UTC (Fri) by marcH (subscriber, #57642) [Link] (1 responses)

> Only force encodings in places where you need that encoding; displaying the file name being the prime example.

Thanks a lot, this clarifies.

So the core issue seems to be: the filename being the only file handle. Lose the name and you lose the file. I agree it shouldn't be like this. For instance you can have an iterator that returns some opaque FileObject that does not really care about the name. Does Python have this?

bytes vs. characters

Posted Apr 25, 2015 8:19 UTC (Sat) by peter-b (guest, #66996) [Link]

> So the core issue seems to be: the filename being the only file handle. Lose the name and you lose the file. I agree it shouldn't be like this. For instance you can have an iterator that returns some opaque FileObject that does not really care about the name. Does Python have this?

Yes. listdir(x) where x is bytes returns the raw filenames as bytes.

https://docs.python.org/3.4/library/os.html?highlight=lis...

bytes vs. characters

Posted Apr 23, 2015 22:11 UTC (Thu) by lopgok (guest, #43164) [Link] (3 responses)

Mission critical is not hard real-time. Mission critical means the mission fails when the program fails to read files in a directory.

Some failures are just annoying, but this one is not for me.

bytes vs. characters

Posted Apr 23, 2015 22:40 UTC (Thu) by marcH (subscriber, #57642) [Link] (2 responses)

> Mission critical means the mission fails when the program fails to read files in a directory.

And the question was: what kind of mission relies on filename garbage?

It's not 100% clear if you actually care about the filenames, or not and just their content.

BTW I totally agree that silently skipping broken filenames is a massive bug.

bytes vs. characters

Posted Apr 24, 2015 0:44 UTC (Fri) by Cyberax (✭ supporter ✭, #52523) [Link] (1 responses)

> And the question was: what kind of mission relies on filename garbage?
For example, a cloud storage client that is used to backup users' files.

bytes vs. characters

Posted May 9, 2015 21:36 UTC (Sat) by nix (subscriber, #2304) [Link]

That would be a backup program written by someone who doesn't understand the difference between Python's byte- and string-based interfaces. I wouldn't trust any backup program written by someone who didn't understand that! God only knows what it's doing to the file content...


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds