X Tutup
The Wayback Machine - https://web.archive.org/web/20240106171007/https://github.com/python/cpython/issues/113251
Skip to content
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

Adding length or length hint to IP networks in the ipaddress module #113251

Open
bartbroere opened this issue Dec 18, 2023 · 1 comment
Open

Adding length or length hint to IP networks in the ipaddress module #113251

bartbroere opened this issue Dec 18, 2023 · 1 comment
Labels
type-feature A feature request or enhancement

Comments

@bartbroere
Copy link
Contributor

bartbroere commented Dec 18, 2023

Feature or enhancement

Proposal:

Some time ago I submitted a proposal to add length hints to the itertools module. These did not get merged for several valid reasons: #101790

However, since ipaddress is a pure Python module, I think adding length (hints) is less hard to get right here.

Therefore I would like to propose adding __len__ (or __length_hint__) to IPv4Network and IPv6Network. This can be useful for progress reporting (for example when scanning a range of IP addresses).

from operator import length_hint
from ipaddress import IPv4Network

print(len(IPv4Network('10.10.10.0/24')))
# 256
assert len(IPv4Network('10.10.10.0/24')) == len(list(IPv4Network('10.10.10.0/24')))

# or

print(length_hint(IPv4Network('10.10.10.0/24')))
# 256

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

@bartbroere bartbroere added the type-feature A feature request or enhancement label Dec 18, 2023
@bartbroere
Copy link
Contributor Author

Update: Adding this works fine for IPv4Networks, but a large IPv6Network will result in issues with integer sizes:

Traceback (most recent call last):
  File "cpython/Lib/ipaddress.py", line 2350, in <module>
    print(length_hint(IPv6Network('2607:fb10:2018::/45')))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OverflowError: Python int too large to convert to C ssize_t
Traceback (most recent call last):
  File "cpython/Lib/ipaddress.py", line 2350, in <module>
    print(len(IPv6Network('2607:fb10:2018::/45')))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OverflowError: cannot fit 'int' into an index-sized integer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

1 participant
X Tutup