-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
ipaddress should accept bytearray in addition to bytes #78646
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Hi, the ipaddress module accepts Should this be supported too?
>>> ipaddress.IPv4Address(bytes([127, 0, 0, 1]))
IPv4Address('127.0.0.1')
>>> ipaddress.IPv4Address(bytearray([127, 0, 0, 1]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/ipaddress.py", line 1301, in __init__
self._ip = self._ip_int_from_string(addr_str)
File "/usr/lib/python3.7/ipaddress.py", line 1135, in _ip_int_from_string
raise AddressValueError("Expected 4 octets in %r" % ip_str)
ipaddress.AddressValueError: Expected 4 octets in "bytearray(b'\\x7f\\x00\\x00\\x01')" |
I think it should be supported too. How about a list of bytes? eg : [127,0,0,1].. Should that be supported as well? |
What is your use case? New features can be added only in the developed version. |
My use case is parsing binary data. For that I use a bytearray as a buffer. buf[:4] gets me another bytearray which I'd want to convert to an ipaddress. I can't think of a usecase for list-of-int. |
Why not just bytes(buf[:4]) before passing? |
That's what I'm doing now. |
I'm -1 on this change. I think the workaround is easy and direct. |
This isn't limited to just IPv4Address, the Network classes and the IPv6 classes that accept bytes should also be updated for consistency if we're going to do this. (bytes, bytearray, memoryview) make sense to support, and explicitly test in unittests. Until then, the workaround is to call bytes on the relevant slice of those. |
See bpo-27572 for moving in opposite direction. Supporting the buffer protocol rather of just bytes and bytearray complicates the code, and can be considered as a feature creep, especially if an input is a text encoded as bytes. But in this case the bytes argument of IPv4Address() is not a text representation like b'127.0.0.1', but a packed array of bytes like bytes([127, 0, 0, 1]). Accepting bytearray and memoryview makes more sense for it. Yet I'm not sure that supporting them is worth adding an overhead. This will affect every call of the IPv4Address constructor, and I think that this is not the most common case. Maybe add a special purposed named constructor IPv4Address.from_bytes() that will accept any objects supporting the buffer protocol? |
That would work for me. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: