Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I hit this TypeError exception recently, which I found very difficult to debug. I eventually reduced it to this small test case:

>>> "{:20}".format(b"hi")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__

This is very non-obvious, to me anyway. The workaround for my code was to decode the byte string into unicode:

 >>> "{:20}".format(b"hi".decode("ascii"))
 'hi                  '

What is the meaning of this exception? Is there a way it can be made more clear?

share|improve this question
5  
Probably worth noting: this only became a TypeError in Python 3.4+, and it affects anything that inherits from object without defining __format__ along the way (e.g. None; class T(object): pass, etc.). – Henry Keiter Jul 8 '14 at 13:54
1  
For background information see bugs.python.org/issue7994 – gerrit Mar 19 '15 at 23:25
up vote 22 down vote accepted

bytes objects do not have a __format__ method of their own, so the default from object is used:

>>> bytes.__format__ is object.__format__
True
>>> '{:20}'.format(object())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__

It just means that you cannot use anything other than straight up, unformatted unaligned formatting on these. Explicitly convert to a string object (as you did by decoding bytes to str) to get format spec support.

You can make the conversion explicit by using the !s string conversion:

>>> '{!s:20s}'.format(b"Hi")
"b'Hi'               "
>>> '{!s:20s}'.format(object())
'<object object at 0x1100b9080>'

object.__format__ explicitly rejects format strings to avoid implicit string conversions, specifically because formatting instructions are type specific.

share|improve this answer
4  
makes sense, thanks! I wish the error were more intuitive though! – Chris AtLee Jun 12 '14 at 15:38

This also happens when trying to format None:

>>> '{:.0f}'.format(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__

That took a moment to work out (in my case, when None was being returned by an instance variable)!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.