What is difference between str.format_map(mapping) and str.format What is difference between str.format_map(mapping) and str.format python-3.x python-3.x

What is difference between str.format_map(mapping) and str.format


str.format(**kwargs) makes a new dictionary in the process of calling. str.format_map(kwargs) does not. In addition to being slightly faster, str.format_map() allows you to use a dict subclass (or other object that implements mapping) with special behavior, such as gracefully handling missing keys. This special behavior would be lost otherwise when the items were copied to a new dictionary.

See: https://docs.python.org/3/library/stdtypes.html#str.format_map


str.format(**mapping) when called creates a new dictionary, whereas str.format_map(mapping) doesn't. The format_map(mapping) lets you pass missing keys. This is useful when working per se with the dict subclass.

class Foo(dict): # inheriting the dict class    def __missing__(self,key):        return keyprint('({x},{y})'.format_map(Foo(x='2')))  # missing key y print('({x},{y})'.format_map(Foo(y='3')))  # missing key x


Here's another thing you can't do with .format(**kwargs):

>>> class UserMap:    def __getitem__(self, key):        return input(f"Enter a {key}: ")>>> mad_lib = "I like to {verb} {plural noun} and {plural noun}.".format_map(UserMap())Enter a verb: smellEnter a plural noun: orangesEnter a plural noun: pythons>>> mad_lib'I like to smell oranges and pythons.'

Calling .format(**UserMap()) wouldn't even work because in order to unpack the **kwargs into a dictionary, Python needs to know what all of the keys in the mapping are, which isn't even defined.

Another one:

>>> class NumberSquarer:    def __getitem__(self, key):        return str(int(key.lstrip('n'))**2)    >>> "{n17} is a big number, but {n20} is even bigger.".format_map(NumberSquarer())'289 is a big number, but 400 is even bigger.'

It would be impossible to unpack **NumberSquarer() since it has infinitely many keys!