diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -514,14 +514,21 @@ single: __format__ Convert a *value* to a "formatted" representation, as controlled by - *format_spec*. The interpretation of *format_spec* will depend on the type - of the *value* argument, however there is a standard formatting syntax that - is used by most built-in types: :ref:`formatspec`. + *format_spec*. If *format_spec* is omitted, it defaults to the empty + string ``''``. The interpretation of *format_spec* depends on the type + of the *value* argument. However, there is a standard formatting syntax + that is used by most built-in types: :ref:`formatspec`. + + Per :pep:`3101`, the function returns a Unicode object if *format_spec* is + Unicode. Otherwise, it returns an 8-bit string. .. note:: ``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. + The method ``value.__format__(format_spec)`` may return 8-bit strings + for some built-in types when *format_spec* is Unicode. .. versionadded:: 2.6 diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1501,7 +1501,14 @@ def test_format(self): # Test the basic machinery of the format() builtin. Don't test # the specifics of the various formatters - self.assertEqual(format(3, ''), '3') + def assert_type_equal(a, b): + # Helper method to check that format() returns unicode when + # format_spec is unicode, and similarly for 8-bit strings. + self.assertEqual(a, b) + self.assertEqual(type(a), type(b)) + + assert_type_equal(format(3, ''), '3') + assert_type_equal(format(3, u''), u'3') # Returns some classes to use for various tests. There's # an old-style version, and a new-style version @@ -1556,8 +1563,10 @@ # test that: # format(x, '') == str(x) # format(x) == str(x) - self.assertEqual(format(value, ""), str(value)) - self.assertEqual(format(value), str(value)) + # format(x, u'') == unicode(x) + assert_type_equal(format(value, ""), str(value)) + assert_type_equal(format(value), str(value)) + assert_type_equal(format(value, u""), unicode(value)) # for builtin types, format(x, "") == str(x) empty_format_spec(17**13)