MCPcopy Index your code
hub / github.com/python/cpython / __format__

Method __format__

Lib/ipaddress.py:613–660  ·  view source on GitHub ↗

Returns an IP address as a formatted string. Supported presentation types are: 's': returns the IP address as a string (default) 'b': converts to binary and returns a zero-padded string 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string

(self, fmt)

Source from the content-addressed store, hash-verified

611 return self.__class__, (self._ip,)
612
613 def __format__(self, fmt):
614 """Returns an IP address as a formatted string.
615
616 Supported presentation types are:
617 's': returns the IP address as a string (default)
618 'b': converts to binary and returns a zero-padded string
619 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string
620 'n': the same as 'b' for IPv4 and 'x' for IPv6
621
622 For binary and hex presentation types, the alternate form specifier
623 '#' and the grouping option '_' are supported.
624 """
625
626 # Support string formatting
627 if not fmt or fmt[-1] == 's':
628 return format(str(self), fmt)
629
630 # From here on down, support for 'bnXx'
631 global _address_fmt_re
632 if _address_fmt_re is None:
633 import re
634 _address_fmt_re = re.compile('(#?)(_?)([xbnX])')
635
636 m = _address_fmt_re.fullmatch(fmt)
637 if not m:
638 return super().__format__(fmt)
639
640 alternate, grouping, fmt_base = m.groups()
641
642 # Set some defaults
643 if fmt_base == 'n':
644 if self.version == 4:
645 fmt_base = 'b' # Binary is default for ipv4
646 else:
647 fmt_base = 'x' # Hex is default for ipv6
648
649 if fmt_base == 'b':
650 padlen = self.max_prefixlen
651 else:
652 padlen = self.max_prefixlen // 4
653
654 if grouping:
655 padlen += padlen // 4 - 1
656
657 if alternate:
658 padlen += 2 # 0b or 0x
659
660 return format(int(self), f'{alternate}0{padlen}{grouping}{fmt_base}')
661
662
663@functools.total_ordering

Callers

nothing calls this directly

Calls 5

formatFunction · 0.85
strFunction · 0.85
superClass · 0.85
compileMethod · 0.45
groupsMethod · 0.45

Tested by

no test coverage detected