Eric V. Smith added the comment:

David is correct.

It's often easiest to think about the builtin format() instead of str.format(). 
Notice below that the format specifier has to make sense for the object being 
formatted:

>>> import datetime
>>> now = datetime.datetime.now()

>>> format('somestring', '.12s')
'somestring  '

# "works", but not what you want because it calls now.strftime('.12s'):
>>> format(now, '.12s')
'.12s'

# better:
>>> format(now, '%Y-%m-%d')  # better
'2014-03-19'

# int doesn't know what '.12s' format spec means:
>>> format(3, '.12s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 's' for object of type 'int'

# None doesn't have an __format__, so object.__format__ rejects it:
>>> format(None, '.12s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__

# just like a random class doesn't have an __format__:
>>> class F: pass
... 
>>> format(F(), '.12s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__


Tangentially related:

The best you can do here, given your use case, is to argue that None needs an 
__format__ that understands str's format specifiers, because you like to mix 
str and None. But maybe someone else likes to mix int and None. Maybe None 
should understand int's format specifiers, and not str's:

>>> format(42000, ',d')
'42,000'
>>> format('42000', ',d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

Why would "format(None, '.12s')" make any more sense than "format(None, ',d')"? 
Since we can't guess, we chose an error.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue7994>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to