Author jaraco
Recipients ebehar, eric.araujo, eric.smith, ezio.melotti, flox, gruszczy, jaraco, r.david.murray, rhettinger, terry.reedy
Date 2011-01-28.19:20:05
SpamBayes Score 8.79895e-07
Marked as misclassified No
Message-id <1296242406.21.0.437632137333.issue6081@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2011-01-28 19:20:06jaracosetrecipients: + jaraco, rhettinger, terry.reedy, eric.smith, ezio.melotti, eric.araujo, r.david.murray, gruszczy, ebehar, flox
2011-01-28 19:20:06jaracosetmessageid: <1296242406.21.0.437632137333.issue6081@psf.upfronthosting.co.za>
2011-01-28 19:20:05jaracolinkissue6081 messages
2011-01-28 19:20:05jaracocreate