3 ms·
I took some time try to make an old codebase to work with python2/3. Some wat moment from the effort: 1. `StringIO.StringIO` is a PITA. There's no equivalent i
by yegle 9y ago
I took some time try to make an old codebase to work with python2/3. Some wat moment from the effort:
1. `StringIO.StringIO` is a PITA. There's no equivalent in Python3 (for a good reason), and you must choose between `io.StringIO` (which only support unicode) and `io.BytesIO` (which only support bytes string). A possible solution is to use `six.StringIO` but it's simply bury the problem. It would be a good idea to think about what string you are dealing with before doing any change around StringIO.
2. The `stat` module contains some helper functions to test st_mode. In Python2, the function will happily accept negative numbers but in Python3 an exception will throw:
$ python2 -c 'import stat; print(stat.S_ISDIR(-1))'
False
$ python3 -c 'import stat; print(stat.S_ISDIR(-1))'
Traceback (most recent call last):
File "<string>", line 1, in <module>
OverflowError: can't convert negative value to unsigned int
3. You can do `def foo(a, (b, c), d)` in Python2: https://www.python.org/dev/peps/pep-3113/ https://www.python.org/dev/peps/pep-3113/
4. You can compare slice with int in Python2:
$ python2 -c 'print(slice(1) > 1)'
True
$ python3 -c 'print(slice(1) > 1)'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: unorderable types: slice() > int()
- kstrauser 9y agoI think those are all improvements in Python3, even if they can be a hassle to fix: 1. Lots of legacy code incorrectly treats strings and byte arrays as the same thing. If you're dealing 100% with all ASCII all the time that might be mostly OK, but it's the wrong model for anything involving Unicode (which is pretty much everything now). 2. Modes are defined on Linux and macOS at least as uint32_t. -1 isn't a valid value of that type. 3. That bit me a few time. I've accepted that `def foo(a, b_and_c, d): b, c = b_and_c` is an alright substitute. 4. I like the new version better. `'a' > 5` doesn't even make sense and the 3.x way avoids accidental nonsensical comparisons.