Jason R. Coombs <[email protected]> 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 <[email protected]>
<http://bugs.python.org/issue6081>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com