Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e0c3f5e

Browse files
committed
Close #15559: Implementing __index__ creates a nasty interaction with the bytes constructor. At least for 3.3, ipaddress objects must now be explicitly converted with int() and thus can't be passed directly to the hex() builtin.
1 parent 37d3ff1 commit e0c3f5e

2 files changed

Lines changed: 9 additions & 14 deletions

File tree

Lib/ipaddress.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -511,9 +511,6 @@ def __init__(self, address):
511511
and '/' in str(address)):
512512
raise AddressValueError("Unexpected '/' in %r" % address)
513513

514-
def __index__(self):
515-
return self._ip
516-
517514
def __int__(self):
518515
return self._ip
519516

@@ -571,9 +568,6 @@ class _BaseNetwork(_IPAddressBase):
571568
def __init__(self, address):
572569
self._cache = {}
573570

574-
def __index__(self):
575-
return int(self.network_address) ^ self.prefixlen
576-
577571
def __int__(self):
578572
return int(self.network_address)
579573

Lib/test/test_ipaddress.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import unittest
88
import re
99
import contextlib
10+
import operator
1011
import ipaddress
1112

1213
class BaseTestCase(unittest.TestCase):
@@ -72,6 +73,14 @@ def test_floats_rejected(self):
7273
with self.assertAddressError(re.escape(repr("1.0"))):
7374
self.factory(1.0)
7475

76+
def test_not_an_index_issue15559(self):
77+
# Implementing __index__ makes for a very nasty interaction with the
78+
# bytes constructor. Thus, we disallow implicit use as an integer
79+
self.assertRaises(TypeError, operator.index, self.factory(1))
80+
self.assertRaises(TypeError, hex, self.factory(1))
81+
self.assertRaises(TypeError, bytes, self.factory(1))
82+
83+
7584
class CommonTestMixin_v4(CommonTestMixin):
7685

7786
def test_leading_zeros(self):
@@ -599,7 +608,6 @@ def testInternals(self):
599608
self.assertEqual(first, last)
600609
self.assertEqual(128, ipaddress._count_righthand_zero_bits(0, 128))
601610
self.assertEqual("IPv4Network('1.2.3.0/24')", repr(self.ipv4_network))
602-
self.assertEqual('0x1020318', hex(self.ipv4_network))
603611

604612
def testMissingAddressVersion(self):
605613
class Broken(ipaddress._BaseAddress):
@@ -1545,13 +1553,6 @@ def testIntRepresentation(self):
15451553
self.assertEqual(42540616829182469433547762482097946625,
15461554
int(self.ipv6_address))
15471555

1548-
def testHexRepresentation(self):
1549-
self.assertEqual(hex(0x1020304),
1550-
hex(self.ipv4_address))
1551-
1552-
self.assertEqual(hex(0x20010658022ACAFE0200000000000001),
1553-
hex(self.ipv6_address))
1554-
15551556
def testForceVersion(self):
15561557
self.assertEqual(ipaddress.ip_network(1).version, 4)
15571558
self.assertEqual(ipaddress.IPv6Network(1).version, 6)

0 commit comments

Comments
 (0)