Skip to content

Shorthand IPv4Network and IPv6Network #128810

Closed as not planned
Closed as not planned
@jfuruness

Description

@jfuruness

Feature or enhancement

Proposal:

IPv4Networks and IPv6Networks are often written in shorthand by network operators. For example, 1.2.0.0/16 would be written as 1.2/16. I've added a very simple .shorthand function (along with a few simple tests) to these networks in the hopes that this can be a supported feature.

For the IPv4Network:

    @property
    def shorthand(self):
        """
        Returns the shorthand representation of the IPv4 network.

        This method abbreviates the IPv4 network by removing trailing
        zero octets from the network address.

        Returns:
            str: The shorthand IPv4 network in the format 'X.X/X'.

        Example:
            >>> network = IPv4Network('192.168.0.0/24')
            >>> network.shorthand
            '192.168/24'
        """
        # Split the network address into octets
        octets = str(self.network_address).split('.')
        # Remove trailing zero octets
        while octets and octets[-1] == '0':
            octets.pop()
        # Rejoin the remaining octets and append the prefix length
        return '.'.join(octets) + f"/{self.prefixlen}"

For the IPv6Network:

    @property
    def shorthand(self):
        """
        Returns the shorthand representation of the IPv6 network.

        This method compresses the IPv6 address to its shortest form
        and appends the prefix length.

        Returns:
            str: The shorthand IPv6 network in the format 'X::/Y'.

        Example:
            >>> network = IPv6Network('2001:db8:0:0:0:0:0:0/32')
            >>> network.shorthand
            '2001:db8::/32'
        """
        return f"{self.network_address.compressed}/{self.prefixlen}"

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

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions