diff options
author | Roy Williams <rwilliams@lyft.com> | 2016-09-21 18:39:07 -0700 |
---|---|---|
committer | Roy Williams <rwilliams@lyft.com> | 2016-09-21 18:48:42 -0700 |
commit | 8f8a95e568df1fe5eee1833a8553617f0cae7dfa (patch) | |
tree | 029356bc6b16169fa379360643c53d43122f2d15 | |
parent | 4b1dab370f8a32aaa3f9140c38645093d3287b82 (diff) | |
download | simplejson-8f8a95e568df1fe5eee1833a8553617f0cae7dfa.tar.gz |
Use `codecs.decode` in Python 2 as opposed to `str.decode` in Python 2.
I am investigating a migration to Python 3, and to facilitate this we are using the `-3` flag as decribed here:
https://docs.python.org/3/howto/pyporting.html#prevent-compatibility-regressions . When using this flag,
I get warnings from simplejson about the use of decode.
While obviously this is a invalid warning since this code is gated in Python 2, committing this change
will allow users to run their code in `-3` mode in Python 2 without warnings from simplejson.
Microbenchmarking this change with `timeit` also reveals it's faster!
```py
>>> import timeit
>>> timeit.timeit("decode_hex('4f6c6567')[0]", setup="import codecs; decode_hex = codecs.getdecoder('hex_codec')")
0.6572110652923584
>>> timeit.timeit("'4f6c6567'.decode('hex')")
0.9076640605926514
```
-rw-r--r-- | simplejson/compat.py | 5 |
1 files changed, 3 insertions, 2 deletions
diff --git a/simplejson/compat.py b/simplejson/compat.py index a0af4a1..50d1f0c 100644 --- a/simplejson/compat.py +++ b/simplejson/compat.py @@ -1,5 +1,6 @@ """Python 3 compatibility shims """ +import codecs import sys if sys.version_info[0] < 3: PY3 = False @@ -15,8 +16,9 @@ if sys.version_info[0] < 3: integer_types = (int, long) unichr = unichr reload_module = reload + __decode_hex = codecs.getdecoder('hex_codec') def fromhex(s): - return s.decode('hex') + return __decode_hex(s)[0] else: PY3 = True @@ -24,7 +26,6 @@ else: from importlib import reload as reload_module else: from imp import reload as reload_module - import codecs def b(s): return codecs.latin_1_encode(s)[0] def u(s): |