python format spec for int.__format__

Question:

I have reason to want to call int.__format__ directly. I tried the following

>>> object.__format__(1,'d')

But get an exception

TypeError: unsupported format string passed to int.__format__

What should the fmt_spec be?

Asked By: chuck1

||

Answers:

Well, you used object.__format__ not int.__format__. Try one of these instead:

>>> int.__format__(1, 'd')
'1'
>>> (1).__format__('d')
'1'

The behaviour you’re seeing with non-empty string passed to object.__format__ is documented:

Changed in version 3.4: The __format__ method of object itself raises a TypeError if passed any non-empty string.

Answered By: wim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.