[Python-ideas] Extending __format__ method in ipaddress

Nick Coghlan ncoghlan at gmail.com
Wed Feb 14 22:52:13 EST 2018


On 15 February 2018 at 08:29, Eric Osborne <eric at notcom.com> wrote:
>   Nick Coghlan suggested I instead extend __format__, which is what the
> diffs in the current pull request do.  This allows a great deal more
> flexibility: the current code takes 'b', 'n', or 'x' types, as well as the
> '#' option and support for the '_' separator.

+1 from me (unsurprisingly).

We added __format__ specifically to give types more control over how
they're printed, and this approach is amenable to the simple
explanation that the custom IP address formatting works via:

- conversion to int
- printing in a fixed width field (based on the address size)
- in binary or hex based on either the given format character, or the
address size ("n", where IPv4=b and IPv6=x)
- with a suitable prefix if "#" is given
- with four-digit separators if "_" is given

>  I realize now I didn't add
> 'o' but I certainly can for completeness.

I'd suggest leaving it out, as octal characters are 3 bits each, so
they don't have a natural association with IP address representations
any more than decimal representation does (neither 32 nor 128 are
divisible by 3).

>  I debated adding rfc1924 encoding
> for IPv6 addresses but decided it was entirely too silly.

Yeah, if we decided to support that, we likely *would* add a separate
method for it.

__format__ works well for "print an IP address as an integer with
zero-padding and an automatically calculated field width" though,
since we can borrow the notation from regular integer formatting to
select the digit base and tweak the display details.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list