python3 string format

Ian Kelly ian.g.kelly at gmail.com
Tue Mar 26 02:16:48 EDT 2013


On Mon, Mar 25, 2013 at 10:24 PM, Shiyao Ma <i at introo.me> wrote:
> HI.
> one thing confuses me.
> It is said in the pep3101 that "{}".format (x) will invoke the method
> x.__format__
> However, I looked at the src of python3 and found:
> in class str(object), the format simply contains a pass statement
> in class int(object), things is the same.

I don't know what source you're looking at.  In CPython, both of those
types are implemented in C, not Python, so there would be no pass
statements involved.

The int.__format__ method is implemented at:

http://hg.python.org/cpython/file/3c437e591499/Objects/longobject.c#l4373

It mainly just calls the _PyLong_FormatAdvancedWriter function, which is at:

http://hg.python.org/cpython/file/3c437e591499/Python/formatter_unicode.c#l1399

The str.__format__ method similarly is implemented at:

http://hg.python.org/cpython/file/3c437e591499/Objects/unicodeobject.c#l12851

and calls the _PyUnicode_FormatAdvancedWriter function at:

http://hg.python.org/cpython/file/3c437e591499/Python/formatter_unicode.c#l1363



More information about the Python-list mailing list