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

Feature Request: Warn when instance attribute shadows class attribute #15169

Open
alippai opened this issue Dec 28, 2024 · 2 comments
Open

Feature Request: Warn when instance attribute shadows class attribute #15169

alippai opened this issue Dec 28, 2024 · 2 comments
Labels
rule Implementing or modifying a lint rule type-inference Requires more advanced type inference.

Comments

@alippai
Copy link

alippai commented Dec 28, 2024

I suggest adding a linting rule to warn when an instance attribute shadows a class attribute of the same name. This can help prevent bugs from unintended overriding of class-level variables.

class A:
    x = 1
    def get_x(self):
        return self.x

a = A()
a.x = 2  # Shadows class attribute 'x'
print(a.get_x())  # Outputs 2, but class attribute 'x' is 1

In this example, assigning to a.x creates an instance attribute that overshadows the class attribute x. Accessing self.x in get_x now refers to the instance attribute, which might not be the intended behavior.

Similarly, the subclassing is error prone:

class Parent:
    def __init__(self):
        self.value = 'instance'

    def get_value(self):
        return self.value

class Child(Parent):
    value = 'class'  # Class attribute shadows instance attribute

c = Child()
print(c.get_value())  # Outputs 'instance'
@alippai
Copy link
Author

alippai commented Dec 28, 2024

@MichaReiser this might be relevant here: #10891

@MichaReiser MichaReiser added rule Implementing or modifying a lint rule type-inference Requires more advanced type inference. labels Dec 30, 2024
@MichaReiser
Copy link
Member

Thanks for opening this rule idea.

The main challenge with this rule is that it probably requires type inference, or at least more advanced analysis than what Ruff does today to be useful:

  • Ruff needs to understand that a is an instance of A
  • Ideally, Ruff understands that a is an instance of A even if A is defined in another file or if A is the result of a function call
  • Ruff needs to understand whether a.x is an instance attribute or not (I think that's doable because detecting class attributes is "easy enough).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule Implementing or modifying a lint rule type-inference Requires more advanced type inference.
Projects
None yet
Development

No branches or pull requests

2 participants