Skip to content

Instantly share code, notes, and snippets.

@mahmoud
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmoud/74babdf44978914385c5 to your computer and use it in GitHub Desktop.
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()
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__
@mahmoud
Copy link
Author

mahmoud commented Feb 18, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment