Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule request: Warn whenever any default value is provided in __post_init__ #13128

Closed
NeilGirdhar opened this issue Aug 27, 2024 · 4 comments · Fixed by #13192
Closed

Rule request: Warn whenever any default value is provided in __post_init__ #13128

NeilGirdhar opened this issue Aug 27, 2024 · 4 comments · Fixed by #13192
Labels
accepted Ready for implementation help wanted Contributions especially welcome rule Implementing or modifying a lint rule

Comments

@NeilGirdhar
Copy link

NeilGirdhar commented Aug 27, 2024

Default values should not be given in the arguments of __post_init__. They should only be provided as default values for class-level init-only member variables.

from dataclasses import InitVar, dataclass


@dataclass
class C:
    x: InitVar[int] = 1

    def __post_init__(self, x: int = 4) -> None:
        print(x)  # noqa: T201


c = C()  # Prints 1!  4 is ignored.

The above text could be used for the Ruff rule warning message.

@dhruvmanila
Copy link
Member

Interesting, thanks for raising this rule request. This seems like a reasonable rule to implement, most likely in a RUF category. What do you think? @AlexWaygood

@dhruvmanila dhruvmanila added the rule Implementing or modifying a lint rule label Aug 28, 2024
@dhruvmanila
Copy link
Member

@NeilGirdhar
Copy link
Author

Although, I couldn't really find any usages of such pattern

Fair enough. It came up when I was working on my own code. I had accidentally added some parameter defaults, and then I though to check what happens.

That said, if this pattern is that rare, then I agree that there are more important issues to be added to Ruff and we can close this.

@AlexWaygood
Copy link
Member

I agree this is a reasonable thing to have a rule for. There's no chance of false positives, and I think I remember hitting this footgun myself at one point in a previous project. The RUF category sounds good to me.

@AlexWaygood AlexWaygood added accepted Ready for implementation help wanted Contributions especially welcome labels Aug 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
accepted Ready for implementation help wanted Contributions especially welcome rule Implementing or modifying a lint rule
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants