[issue32820] Add __format__ method to ipaddress

Nick Coghlan report at bugs.python.org
Fri Feb 23 23:35:51 EST 2018


Nick Coghlan <ncoghlan at gmail.com> added the comment:

I think supporting "s" makes sense, as we're going to need to treat the empty format string as implying "s" for backwards compatibility reasons:

    >>> f"{v4}"
    '1.2.3.4'

Right now, attempting to format that field without `!s` will give you a TypeError, but as Eric O notes, once IP addresses support __format__, we're going to have to choose between:

- raise an exception if formatting directions are given without a numeric typecode
- ignore the formatting in that case (which is what the current PR does)
- handle it the same way "!s" would (and also allow "s" as an explicit type code)

The last option sounds the most desirable to me, as that way we can just say "'s' is the default IP addressing formatting typecode" (similar to the way 'd' is the default for integers, and 'g' is the default for floating point numbers).

I *don't* think we should allow combining the numeric typecode with the string type code, though. The numeric types don't allow that, and f-strings already support nesting if you want to combine string formatting with numeric formatting:

    >>> f"{f'{42**100:g}':>20s}"
    '        2.11314e+162'

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32820>
_______________________________________


More information about the Python-bugs-list mailing list