MCPcopy Index your code
hub / github.com/RustPython/RustPython / __format__

Method __format__

Lib/ipaddress.py:616–663  ·  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

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

Callers

nothing calls this directly

Calls 6

strFunction · 0.85
superClass · 0.85
fullmatchMethod · 0.80
formatFunction · 0.70
compileMethod · 0.45
groupsMethod · 0.45

Tested by

no test coverage detected