Skip to content

method-receiver-default (RUF077)

Preview (since 0.16.7) · Related issues · View source

Fix is always available.

This rule is unstable and in preview. The --preview flag is required for use.

What it does

Checks for default values on receiver parameters (e.g., self, cls) in method definitions.

Why is this bad?

Receiver parameters (self, cls, or any name used as the receiver) should not have default values. In practice, these parameters are usually bound by the method binding protocol, so a default value on a receiver parameter is almost certainly a mistake and can lead to confusing behavior or runtime errors.

Example

class A:
    def method(self=None): ...

    @classmethod
    def build(cls=None): ...

Use instead:

class A:
    def method(self): ...

    @classmethod
    def build(cls): ...

Fix safety

This fix is always marked as unsafe. Removing the default changes behavior for a caller that invokes the method directly through the class rather than through an instance (e.g. A.method() instead of A().method()), relying on the receiver parameter's default value.

Known limitations

To avoid false positives, this rule only flags an undecorated method, an undecorated __new__, or a method whose sole decorator is the one that makes it a @classmethod. A method with any other decorator (including common ones like @property, @x.setter, or @typing.override) is not flagged, even though such decorators typically leave the receiver binding unchanged, because an arbitrary decorator could alter it.

Options