flake8-bugbear icon indicating copy to clipboard operation
flake8-bugbear copied to clipboard

B903 reword message when a subclass is involved

Open ezyang opened this issue 5 years ago • 7 comments

The current B903 message reads:

B903 Data class should either be immutable or use slots to save memory. Use collections.namedtuple to generate an immutable class, or enumerate the attributes in a slot declaration in the class to leave attributes mutable.

However, this lint message is not totally correct if the data class in question inherits from another class; e.g., Exception; in this case, use of namedtuple is inappropriate (actually, I'm not sure if there's any other way to do it.)

ezyang avatar Mar 19 '19 17:03 ezyang

We ran into the very same issue.

tobias-farrenkopf avatar Jan 22 '20 16:01 tobias-farrenkopf

Yes, this is idiomatic python, which means we had to disable this check every time we wrote

class MyError(ValueError):
    """MyError is raised when bla bla bla..."""

olliemath avatar Feb 16 '21 10:02 olliemath

So this check was added before Data Classes existed. What's a proposed solution here? Want to check for this inheritance and disable the error if that's found? We would need to clearly explain it in the documentation.

cooperlees avatar Feb 16 '21 13:02 cooperlees

I think that's the most sensible option. It's not perfect, but you'd still catch simple dataclasses and leave more advanced types alone.

Since you can't inspect the MRO in the syntax tree without a lot of effort, it's not practical to do anything more advanced

olliemath avatar Feb 17 '21 14:02 olliemath

Want to check for this inheritance and disable the error if that's found? We would need to clearly explain it in the documentation.

Checking inheritance would make sense. In my case I came across a

    class MockStripeObj(dict):
        def __init__(self, param):
            self.id = param
            self.type = param

which triggered this opinionated warning and, like above, I’m silencing it as a false positive. If there were no base class(es) (i.e. implicit object) then the warning would be valid.

We would need to clearly explain it in the documentation.

Yup. Probably would make sense to mention something like, “Is this meant to be a dataclass?” or some such?

jenstroeger avatar Oct 04 '22 03:10 jenstroeger

I'm also hitting this on Exception classes

tolomea avatar Dec 19 '22 18:12 tolomea

super in the init shuts it up...

tolomea avatar Dec 19 '22 19:12 tolomea