New submission from Mahmoud Hashemi: While porting some old code, I found some interesting misbehavior in the new-style string formatting. When formatting objects which support int and float conversion, old-style percent formatting works great, but new-style formatting explodes hard.
Here's a basic example: class MyType(object): def __init__(self, func): self.func = func def __float__(self): return float(self.func()) print '%f' % MyType(lambda: 3) # Output (python2 and python3): 3.000000 print '{:f}'.format(MyType(lambda: 3)) # Output (python2): # Traceback (most recent call last): # File "tmp.py", line 28, in <module> # print '{:f}'.format(MyType(lambda: 3)) # ValueError: Unknown format code 'f' for object of type 'str' # # Output (python3.4): # Traceback (most recent call last): # File "tmp.py", line 30, in <module> # print('{:f}'.format(MyType(lambda: 3))) # TypeError: non-empty format string passed to object.__format__ And the same holds true for int and so forth. I would expect these behaviors to be the same between the two formatting styles, and tangentially, expect a more python2-like error message for the python 3 case. ---------- messages: 236192 nosy: mahmoud priority: normal severity: normal status: open title: str.format() breaks object duck typing type: behavior versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6 _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue23479> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com