Python's standard library is awesome. Just skim through the list of available packages and modules. I bet that there is something in there that you didn't know existed or that you have forgotten about it. From time to time I like to go through this list or check the Python release notes to see if there is any addition that can make my life easier.
It is not uncommon to forget about it and implement some functionality that already exists from scratch, and it's probably implemented in a better way. In other words, it's easy to reimplement the wheel.
A clear example of that is a blog post I stumbled into a few weeks ago, which describes a way of checking if an IP belongs to a subnetwork. The solution on that blog post takes 83 lines of code (31 are docstrings), split into three functions: a main function and two auxiliary. With the help of the ipaddress package from the standard library, it can be reduced to only 20 lines (9 are docstrings) and a single function, as the code is short enough for that:
import ipaddress
def ip_in_subnetwork(ip_address, subnetwork):
"""
Returns True if the provided IP address belongs to the
subnetwork (specified in CIDR notation); otherwise, returns
False. Both arguments should be strings.
Supports both IPv4 (e.g., '192.168.1.1' and '192.168.1.0/24')
and IPv6 (e.g., '2a02:a448:ddb0::' and '2a02:a448:ddb0::/44')
addresses and subnetworks.
"""
address = ipaddress.ip_address(ip_address)
network = ipaddress.ip_network(subnetwork)
if address.version != network.version:
raise ValueError('Incompatible IP versions')
return address in network
I want to make it clear that my intention is not to dunk on that other blog post, but I thought it was a real and good example of what can happen to anybody who doesn't know that what they need already exists. Notice that the author leverages two other packages from the standard library!
In all fairness, their solution works on both Python 2 and 3, while mine is 3.3+ only. But, notice how for readers interested in a Python 3-only solution, they recommend using the 3rd party package netaddr, which makes me think the author just didn't know of the existence of ipaddress.
Happy coding!