Skip to content

Commit

Permalink
Use operator.index to avoid DeprecationWarning on Python 2
Browse files Browse the repository at this point in the history
Fixes #79

Slightly faster on CPython:

$ python -m perf timeit -s 'from struct import Struct; s = Struct("i"); unpack=s.unpack; pack=s.pack' 'unpack(pack(123456))'
.....................
Mean +- std dev: 252 ns +- 12 ns
$ python -m perf timeit -s 'from struct import Struct; s = Struct("i"); from operator import index; pack=s.pack' 'pack(index(123456))'
.....................
Mean +- std dev: 235 ns +- 6 ns

Very slightly faster on PyPy:

python -m perf timeit -s 'from struct import Struct; s = Struct("i"); unpack=s.unpack; pack=s.pack' 'unpack(pack(123456))'
.........
Mean +- std dev: 4.24 ns +- 0.12 ns
$ python -m perf timeit -s 'from struct import Struct; s = Struct("i"); from operator import index; pack=s.pack' 'pack(index(123456))'
.........
Mean +- std dev: 4.19 ns +- 0.10 ns
  • Loading branch information
jamadden committed Mar 9, 2018
1 parent 023d96a commit 4debe1b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
19 changes: 5 additions & 14 deletions BTrees/_base.py
Expand Up @@ -16,6 +16,7 @@

from struct import Struct
from struct import error as struct_error
from operator import index

from persistent import Persistent

Expand Down Expand Up @@ -1503,12 +1504,8 @@ def _packer_unpacker(struct_format):

def to_int(self, v):
try:
# XXX Python 2.6 doesn't truncate, it spews a warning.
if not int_unpack(int_pack(v))[0] == v: #pragma: no cover
raise TypeError('32-bit integer expected')
except (struct_error,
OverflowError, #PyPy
):
int_pack(index(v))
except (struct_error, TypeError):
raise TypeError('32-bit integer expected')

return int(v)
Expand All @@ -1527,14 +1524,8 @@ def to_float(self, v):

def to_long(self, v):
try:
# XXX Python 2.6 doesn't truncate, it spews a warning.
if not long_unpack(long_pack(v))[0] == v: #pragma: no cover
if isinstance(v, int_types):
raise ValueError("Value out of range", v)
raise TypeError('64-bit integer expected')
except (struct_error,
OverflowError, #PyPy
):
long_pack(index(v))
except (struct_error, TypeError):
if isinstance(v, int_types):
raise ValueError("Value out of range", v)
raise TypeError('64-bit integer expected')
Expand Down
5 changes: 4 additions & 1 deletion CHANGES.rst
Expand Up @@ -14,7 +14,10 @@
- Respect the ``PURE_PYTHON`` environment variable at runtime even if
the C extensions are available. See
https://github.com/zopefoundation/BTrees/issues/78
- Always attempt to build the C extensions, but make their success optional.
- Always attempt to build the C extensions, but make their success
optional.
- Fix a ``DeprecationWarning`` that could come from I and L objects in
Python 2 in pure-Python mode. See https://github.com/zopefoundation/BTrees/issues/79

4.4.1 (2017-01-24)
------------------
Expand Down

0 comments on commit 4debe1b

Please sign in to comment.