Skip to content

Commit bb3d9b4

Browse files
committed
Make Multiaddr a “copy-constructor” and use it where we except any MultiAddr to be more flexible about the types we may receive
1 parent a3c94be commit bb3d9b4

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

multiaddr/multiaddr.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
except ImportError: # pragma: no cover (PY2)
55
import collections
66
collections.abc = collections
7-
from copy import copy
87

98
import six
109

@@ -120,8 +119,10 @@ def __init__(self, addr):
120119
self._bytes = string_to_bytes(addr)
121120
elif isinstance(addr, six.binary_type):
122121
self._bytes = addr
122+
elif isinstance(addr, Multiaddr):
123+
self._bytes = addr.to_bytes()
123124
else:
124-
raise TypeError("MultiAddr must be bytes or str")
125+
raise TypeError("MultiAddr must be bytes, str or another MultiAddr instance")
125126

126127
def __eq__(self, other):
127128
"""Checks if two Multiaddr objects are exactly equal."""
@@ -179,7 +180,7 @@ def encapsulate(self, other):
179180
/ip4/1.2.3.4 encapsulate /tcp/80 = /ip4/1.2.3.4/tcp/80
180181
"""
181182
mb = self.to_bytes()
182-
ob = other.to_bytes()
183+
ob = Multiaddr(other).to_bytes()
183184
return Multiaddr(b''.join([mb, ob]))
184185

185186
def decapsulate(self, other):
@@ -189,12 +190,12 @@ def decapsulate(self, other):
189190
/ip4/1.2.3.4/tcp/80 decapsulate /ip4/1.2.3.4 = /tcp/80
190191
"""
191192
s1 = self.to_bytes()
192-
s2 = other.to_bytes()
193+
s2 = Multiaddr(other).to_bytes()
193194
try:
194195
idx = s1.rindex(s2)
195196
except ValueError:
196197
# if multiaddr not contained, returns a copy
197-
return copy(self)
198+
return Multiaddr(self)
198199
return Multiaddr(s1[:idx])
199200

200201
def value_for_protocol(self, proto):

0 commit comments

Comments
 (0)