[docs] [issue15952] format(value) and value.__format__() behave differently with unicode format

Ezio Melotti report at bugs.python.org
Sun Sep 23 13:15:11 CEST 2012

Ezio Melotti added the comment:

``format(value, format_spec)`` merely calls
-      ``value.__format__(format_spec)``.
+      ``value.__format__(format_spec)`` and, if *format_spec* is Unicode,
+      converts the value to Unicode if it is not already Unicode.

This is correct, but should be rephrased (and "value" should be "return value").

+      The method ``value.__format__(format_spec)`` may return 8-bit strings
+      for some built-in types when *format_spec* is Unicode.

This is not limited to built-in types.  __format__() might return either str or unicode, and format() returns the same -- except for the aforementioned case.

This is a summary of the possible cases.

__format__ can return unicode or str:

  >>> class Uni(object):
  ...   def __format__(*args): return u'uni'
  >>> class Str(object):
  ...   def __format__(*args): return 'str'

format() and __format__ return the same value, except when the format_spec is unicode and __format__ returns str:

  >>> format(Uni(),  'd'),  Uni().__format__( 'd')  # same
  (u'uni', u'uni')
  >>> format(Uni(), u'd'),  Uni().__format__(u'd')  # same
  (u'uni', u'uni')
  >>> format(Str(),  'd'),  Str().__format__( 'd')  # same
  ('str', 'str')
  >>> format(Str(), u'd'),  Str().__format__(u'd')  # different
  (u'str', 'str')

It is also not true that the type of return value is the same of the format_spec, because in the first case the returned type is unicode even if the format_spec is str.  Therefore this part of the patch should be changed:

+   Per :pep:`3101`, the function returns a Unicode object if *format_spec* is
+   Unicode.  Otherwise, it returns an 8-bit string.

The behavior might be against PEP 3101 (see quotation in msg170669), even thought the wording of the PEP is somewhat lenient IMHO ("proper type" doesn't necessary mean "same type").


Python tracker <report at bugs.python.org>

More information about the docs mailing list