Search code examples
pythonstringclassself

Why doesn't string.Formatter.format have a "self" parameter?


When reading the source code of the string module of python, I am confused by the class Formatter.

The format method (not static nor class method) in the Formatter class does NOT have self as input parameter def format(*args, **kwargs):, but somehow use it directly within the method. self, *args = args.

Please explain this usage.

class Formatter:
    def format(*args, **kwargs):
        if not args:
            raise TypeError("descriptor 'format' of 'Formatter' object "
                            "needs an argument")
        self, *args = args  # allow the "self" keyword be passed
        try:
            format_string, *args = args # allow the "format_string" keyword be passed
        except ValueError:
            if 'format_string' in kwargs:
                ...
            else:
                ...
        return self.vformat(format_string, args, kwargs)

Solution

  • self is assumed to be the first arg in *args, and unpacked in this line:

    self, *args = args

    Declaring an instance method without self in the signature is unusual in Python.

    By looking at the git history for the method signature line we can see that originally self was present.

    It was removed because its presence caused an error if the format string contained a variable named self, for example 'I am my{self}'. The unusual pattern of unpacking self from args was introduced to fix the bug.

    The bug report and discussion is here.

    This is an example of the error, from the bug report:

    >>> string.Formatter().format('the self is {self}', self='bozo')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: format() got multiple values for argument 'self'