3 ms·
> It could be argued that the csv module's behaviour is reasonable I don't see how silently printing a binary literal, if that is indeed what it does, is reaso
by int_19h 10y ago
> It could be argued that the csv module's behaviour is reasonable
I don't see how silently printing a binary literal, if that is indeed what it does, is reasonable. Simply put, b"foo" is not meaningful CSV.
What it should do is 1) raise an exception by default, informing the user that they need to be supplying strings and not bytes, and 2) provide an explicit switch to treat binary data as pass-thru, which would be useful in scenarios where you're just reading a file and dumping it elsewhere, and don't want to spend time decoding and then encoding everything.
- guitarbill 10y agoThe docs say that "[a] row must be an iterable of strings or numbers" [0]. So I guess an exception could be raised. However, the docs do tell a lie; non-strings are accepted and get converted to strings. You can pass any object in which has a string representation - including a byte array. It actually wouldn't be too hard to introduce a check for a bytes field, https://hg.python.org/cpython/file/3.6/Modules/_csv.c#l1227 https://hg.python.org/cpython/file/3.6/Modules/_csv.c#l1227 + if (PyBytes_Check(field)) { + append_ok = FALSE; + Py_DECREF(field); + PyErr_SetString(PyExc_TypeError, "Field is bytes"); + } else { This would then raise a TypeError. I don't think this is the right solution. It seems weird to have a special case because people aren't watching what they're putting in. Garbage in, garbage out, consenting adults and all that. [0] https://docs.python.org/3/library/csv.html https://docs.python.org/3/library/csv.html
- int_19h 10y agoYes, "special cases aren't special enough to break the rules". But "practicality beats purity". And "errors should never pass silently"! It's the same kind of thing that leads to safety warning stickers put on products. You may read it and think that it's something so obvious that consenting adults should know better. But then you look at the statistics about how many people did not, and realize that, yeah, a sticker along the lines of "don't stick your finger into a food processor" is actually a good idea. Especially given how cheap it is, and how expensive reattaching fingers is... Basically, products should be designed around known human weaknesses, and that includes entrenched modes of thinking by past products. It doesn't mean that new products should accommodate those entrenched modes, especially when they lead to other problems. But they should try to detect them, and issue clear and explicit warnings, to guide the person to the proper way of doing things.