Message127325
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. |
|
Date |
User |
Action |
Args |
2011-01-28 19:20:06 | jaraco | set | recipients:
+ jaraco, rhettinger, terry.reedy, eric.smith, ezio.melotti, eric.araujo, r.david.murray, gruszczy, ebehar, flox |
2011-01-28 19:20:06 | jaraco | set | messageid: <1296242406.21.0.437632137333.issue6081@psf.upfronthosting.co.za> |
2011-01-28 19:20:05 | jaraco | link | issue6081 messages |
2011-01-28 19:20:05 | jaraco | create | |
|