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')
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@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/4OHZ6QZWDI3U2ADI5A36UU73OOXFOGJE/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to