Add __len__ to ipaddress._BaseNetwork

Currently, ipaddress._BaseNetwork (and by extension, ipaddress.IPv4Network and ipaddress.IPv6Network) does not have a __len__ method, it only has num_addresses. This makes the following code not work:
random.choice(ipaddress.ip_network('6.0.0.0/8')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/nyuszika7h/.pyenv/versions/3.10.0/lib/python3.10/random.py", line 378, in choice return seq[self._randbelow(len(seq))] TypeError: object of type 'IPv4Network' has no len()
The workaround is a bit ugly:
(network := ipaddress.ip_network('6.0.0.0/8'))[random.randrange(network.num_addresses)] IPv4Address('6.60.184.142')
With a custom subclass, all works well:
class MyIPv4Network(ipaddress.IPv4Network): ... def __len__(self): ... return self.num_addresses ... random.choice(MyIPv4Network('6.0.0.0/8')) IPv4Address('6.40.110.63')

BEst thing you can do is create an issue on bugs.python.org and attach a pull request that makes _BaseNetwork a subclass of Sequence. Then maybe the advantages will be clear -- or maybe in the process of writing the code you realize that the idea is not so good after all. (I'm not a user of this class so I don't have an opinion either way.) On Tue, Oct 26, 2021 at 6:41 AM <nyuszika7h@gmail.com> wrote:
Currently, ipaddress._BaseNetwork (and by extension, ipaddress.IPv4Network and ipaddress.IPv6Network) does not have a __len__ method, it only has num_addresses.
This makes the following code not work:
random.choice(ipaddress.ip_network('6.0.0.0/8')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/nyuszika7h/.pyenv/versions/3.10.0/lib/python3.10/random.py", line 378, in choice return seq[self._randbelow(len(seq))] TypeError: object of type 'IPv4Network' has no len()
The workaround is a bit ugly:
(network := ipaddress.ip_network(' 6.0.0.0/8'))[random.randrange(network.num_addresses <http://6.0.0.0/8'))%5Brandom.randrange(network.num_addresses>)] IPv4Address('6.60.184.142')
With a custom subclass, all works well:
class MyIPv4Network(ipaddress.IPv4Network): ... def __len__(self): ... return self.num_addresses ... random.choice(MyIPv4Network('6.0.0.0/8')) IPv4Address('6.40.110.63')
Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/4OHZ6Q... Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido) *Pronouns: he/him **(why is my pronoun here?)* <http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-c...>
participants (2)
-
Guido van Rossum
-
nyuszika7h@gmail.com