ruff/crates/ruff_python_semantic/src
Brent Westbrook bc7274d148
Add a ScopeKind for the __class__ cell (#20048)
Summary
--

This PR aims to resolve (or help to resolve) #18442 and #19357 by
encoding the CPython semantics around the `__class__` cell in our
semantic model. Namely,

> `__class__` is an implicit closure reference created by the compiler
if any methods in a class body refer to either `__class__` or super.

from the Python
[docs](https://docs.python.org/3/reference/datamodel.html#creating-the-class-object).

As noted in the variant docs by @AlexWaygood, we don't fully model this
behavior, opting always to create the `__class__` cell binding in a new
`ScopeKind::DunderClassCell` around each method definition, without
checking if any method in the class body actually refers to `__class__`
or `super`.

As such, this PR fixes #18442 but not #19357.

Test Plan
--

Existing tests, plus the tests from #19783, which now pass without any
rule-specific code.

Note that we opted not to alter the behavior of F841 here because
flagging `__class__` in these cases still seems helpful. See the
discussion in
https://github.com/astral-sh/ruff/pull/20048#discussion_r2296252395 and
in the test comments for more information.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Co-authored-by: Mikko Leppänen <mleppan23@gmail.com>
2025-08-26 09:49:08 -04:00
..
analyze [ty] Make Module a Salsa ingredient 2025-07-23 09:46:40 -04:00
cfg Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
model [ty] AST garbage collection (#18482) 2025-06-13 08:40:11 -04:00
binding.rs Add a ScopeKind for the __class__ cell (#20048) 2025-08-26 09:49:08 -04:00
branches.rs Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
context.rs Remove separate ReferenceContext enum (#4631) 2023-05-24 15:12:38 +00:00
definition.rs [ty] Make Module a Salsa ingredient 2025-07-23 09:46:40 -04:00
globals.rs [ty] AST garbage collection (#18482) 2025-06-13 08:40:11 -04:00
imports.rs Update Rust toolchain to 1.89 (#19807) 2025-08-07 18:21:50 +02:00
lib.rs Control flow graph: setup (#17064) 2025-04-01 05:53:42 -05:00
model.rs Add a ScopeKind for the __class__ cell (#20048) 2025-08-26 09:49:08 -04:00
nodes.rs Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
reference.rs Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
scope.rs Add a ScopeKind for the __class__ cell (#20048) 2025-08-26 09:49:08 -04:00
star_import.rs Make ImportFrom level just a u32 (#11170) 2024-04-26 20:38:35 -06:00