astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.6k stars 1.09k forks source link

[`flake8-slots`] Rule `SLOT002` doesn't take `typing.NamedTuple` into account #10805

Closed autinerd closed 7 months ago

autinerd commented 7 months ago

Hello :blush:

While adding the SLOT rules to Home Assistant, I found that the SLOT002 doesn't take subclasses of typing.NamedTuple in account, although they are the typed version of collections.namedtuple.

Thanks in advance!

AlexWaygood commented 7 months ago

Hi, thanks for opening the issue! Can you give a minimal code snippet as an example of where you think this rule should be emitting an error but isn't currently?

AlexWaygood commented 7 months ago

Ah, do you mean something like this?

from typing import NamedTuple

class Foo(NamedTuple("Foo", [("x", int)])):
    pass

It's unusual to inherit from a call-based typing.NamedTuple rather than to do something like

from typing import NamedTuple

class Foo(NamedTuple):
    x: int

And if you create a class-based typing.NamedTuple (the second way), it will create the __slots__ for you. But I suppose if you do inherit from a call-based typing.NamedTuple, we probably should emit the diagnostic the same as if it were a collections.namedtuple (and we currently don't).

autinerd commented 7 months ago

Oh, I didn't know that this example:

from typing import NamedTuple

class Foo(NamedTuple):
    x: int

will have the __slots__ automatically created, then it is not needed of course, thanks.

And I didn't know about the call-based NamedTuple as well :sweat_smile: (it is not used in the Home Assistant codebase), but that would be a good idea to add.