From ee063ce26ba748b1b6686cb1802ed32d5cdf44c6 Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Thu, 29 Mar 2018 12:15:40 -0500 Subject: [PATCH 1/2] Scalar comparison semantics We are OK with comparing to ipaddress objects. We raise when comparing to other things. In particular, we even raise when compared to integers or strings that look like ip addresses. --- cyberpandas/ip_array.py | 15 +++++++++++---- tests/ip/test_ip.py | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/cyberpandas/ip_array.py b/cyberpandas/ip_array.py index cafb7ea..408aa62 100644 --- a/cyberpandas/ip_array.py +++ b/cyberpandas/ip_array.py @@ -286,10 +286,17 @@ def to_bytes(self): # ------------------------------------------------------------------------ def __eq__(self, other): - # TDOO: scalar ipaddress - if not isinstance(other, IPArray): - return NotImplemented - mask = self.isna() | other.isna() + if isinstance(other, (ipaddress.IPv4Address, ipaddress.IPv6Address)): + other = int(other) + hi, lo = unpack(pack(other)) + other = np.array([(hi, lo)], dtype=self.dtype._record_type) + mask = self.isna() + elif isinstance(other, IPArray): + mask = self.isna() | other.isna() + else: + msg = ("Invalid type comparison. Can't compare IPArray to " + "type '{}'.") + raise TypeError(msg.format(other)) result = self.data == other.data result[mask] = False return result diff --git a/tests/ip/test_ip.py b/tests/ip/test_ip.py index 6bb9d5d..fa1c1b8 100644 --- a/tests/ip/test_ip.py +++ b/tests/ip/test_ip.py @@ -112,6 +112,27 @@ def test_equality(): v1.equals("a") +@pytest.mark.parametrize('other', [ + 1, '192.168.1.1', b'1' +]) +def test_ops_other(other): + arr = ip.IPArray([1, 2, 3]) + + with pytest.raises(TypeError): + arr == other + + +@pytest.mark.parametrize('other', [ + ipaddress.IPv4Address(1), + ipaddress.IPv6Address(1), +]) +def test_equality_ipaddress(other): + arr = ip.IPArray([0, 1, 2**64 + 1]) + result = arr == other + expected = np.array([False, True, False]) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('op', [ operator.lt, operator.le, From f76a563f28c63b5ffb0d2367bc34d18e9eb9aa6d Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Mon, 2 Apr 2018 10:06:16 -0500 Subject: [PATCH 2/2] Fixed comparison Ensure comparing recarray to recarray --- cyberpandas/ip_array.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cyberpandas/ip_array.py b/cyberpandas/ip_array.py index 408aa62..ab1c85a 100644 --- a/cyberpandas/ip_array.py +++ b/cyberpandas/ip_array.py @@ -293,11 +293,12 @@ def __eq__(self, other): mask = self.isna() elif isinstance(other, IPArray): mask = self.isna() | other.isna() + other = other.data else: msg = ("Invalid type comparison. Can't compare IPArray to " "type '{}'.") raise TypeError(msg.format(other)) - result = self.data == other.data + result = self.data == other result[mask] = False return result