[issue6081] str.format_map()

Jason R. Coombs report at bugs.python.org
Fri Jan 28 20:20:06 CET 2011


Jason R. Coombs <jaraco at jaraco.com> added the comment:

Good work Eric.

When I first heard of new string formatting, I was a little wary. The syntax to supply a dictionary of keyword replacements seemed awkward. It took me a while before I realized why it really bothered me. There's string formatting you can do with the old format operator (%) that you can't do with str.format.

Here's an example.

    import random
    class MyDynamicObject:
        def __getitem__(self, name):
            return name + ' ' + str(random.randint(1,10))

    print("%(foo)s" % MyDynamicObject()) # works!
    print("{foo}".format(**MyDynamicObject())) # can't do that because
MyDynamicObject can't enumerate every possible kwparam

As you can see, the % operator naturally accepts any object that responds to __getitem__ but .format requires that all keyword params be enumerated in advance. This limitation seems to me to be a serious problem to favoring .format over %.

I frequently use % to format the properties of an object... and while
it's true one can use myob.__dict__ or vars(myob) to get a dictionary of
some of the values, that doesn't work for properties and other dynamic
behavior.

format_map addresses this shortcoming nicely. Thanks.

----------
nosy: +jaraco

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6081>
_______________________________________


More information about the Python-bugs-list mailing list