Skip to content

Commit 16d6841

Browse files
committedNov 24, 2019
units: fix __rfloordiv__ handling of unsupported operands
1 parent cf782b1 commit 16d6841

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed
 

‎easypy/units.py

+4
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ def __mul__(self, mul):
7272
__rmul__ = __mul__
7373

7474
def __floordiv__(self, div):
75+
if not isinstance(div, numbers.Number):
76+
return NotImplemented
7577
res = int.__floordiv__(self, div)
7678
if not isinstance(div, self.__class__):
7779
# if div is not a datasize, return a datasize
@@ -80,6 +82,8 @@ def __floordiv__(self, div):
8082
return res
8183

8284
def __rfloordiv__(self, div):
85+
if not isinstance(div, numbers.Number):
86+
return NotImplemented
8387
res = int.__rfloordiv__(self, div)
8488
if not isinstance(div, self.__class__):
8589
# if div is not a datasize, return a datasize

‎tests/test_units.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from easypy.units import byte
1+
from easypy.units import byte, KiB
22

33

44
def test_data_sizes():
@@ -10,3 +10,22 @@ def test_data_sizes():
1010
assert "{0!s}, {0!r}, {0:10text}".format(2**21 * byte) == "2MiB, 2*MiB, 2MiB"
1111
assert "{0!s}, {0!r}, {0:10text}".format(2**21 * byte + 100) == "~2.0MiB, 2097252*bytes, ~2.0MiB"
1212
assert "{0!s}, {0!r}, {0:10text}".format(2**41 * byte + 100) == "~2.0TiB, 2199023255652*bytes, ~2.0TiB"
13+
14+
15+
def test_operators():
16+
17+
assert (byte * 1024) == KiB
18+
assert KiB / 1024 == byte
19+
assert KiB / KiB == 1
20+
assert KiB / 7 == 146.28571428571428
21+
assert KiB // 7 == 146
22+
assert 2050 // KiB == (2 * byte)
23+
24+
# check that __r*__ overloads are used when the unit doesn't support the right-hand operand
25+
class Foo():
26+
def __rfloordiv__(self, div):
27+
return self
28+
29+
foo = Foo()
30+
31+
assert KiB // foo is foo

0 commit comments

Comments
 (0)
Please sign in to comment.