pytype
pytype copied to clipboard
Spurious `duplicate-keyword-argument` error for `str.format` calls with `self` keyword argument
Consider the following snippet:
print("{self}".format(self=42))
When type-checking it with pytype we will get the following error:
File "(...)", line 1, in <module>: function str.format got multiple values for keyword argument 'self' [duplicate-keyword-argument]
Expected: (self, *args, **kwargs)
Actually passed: (self, self)
Note that mypy does not complain about this code. It also executes as expected:
$ python3 -c 'print("{self}".format(self=42))'
42
Interesting that indeed self cannot be used for methods in general. For example, the following:
class Foo:
def bar(self, **kwargs):
print(kwargs)
Foo().bar(self=42)
will fail to execute:
File "(...)", line 7, in <module>
Foo().bar(self=42)
TypeError: bar() got multiple values for argument 'self'
and pytype will correctly catch it:
File "(...)", line 7, in <module>: function Foo.bar got multiple values for keyword argument 'self' [duplicate-keyword-argument]
Expected: (self, **kwargs)
Actually passed: (self, self)
We can fix it with the PEP 570 syntax (positional-only arguments):
class Foo:
def bar(self, /, **kwargs):
print(kwargs)
Foo().bar(self=42)
and execution will succeed and pytype will be happy as well:
Success: no errors found
Interesting that mypy will report an error in neither of these cases (which is wrong!).