Last active
August 29, 2015 14:15
-
-
Save mahmoud/74babdf44978914385c5 to your computer and use it in GitHub Desktop.
Duck-typing and string formatting. Yet another example of percent formatting's superiority over newstyle .format()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyType(object): | |
def __init__(self, func): | |
self.func = func | |
def __int__(self): | |
return int(self.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__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While this is an unintuitive default, the short answer is that this is what
__format__
is for, and the longer answers are here: http://bugs.python.org/issue23479