Repository navigation
[ty] Update __slots__ string when renaming an attribute - #26438
Conversation
lerebear
left a comment
There was a problem hiding this comment.
Thank you for this contribution! It looks good in large part, but I've commented on a pair of bugs that should be addressed before this ships.
|
Thanks for the detailed review @lerebear. I have made the the fix in
One thing that came up while validating the pseudocode is that I added the class-body-annotation test you suggested, plus a regression test for each of the two bugs ( |
Renaming an instance attribute now also updates the matching string in the enclosing class's `__slots__`, the way Pylance does. When the references visitor hits a string literal, it checks whether the string sits in a `__slots__` assignment in a class body (tuple, list, set, or dict keys) and whether the attribute being renamed belongs to that same class. If so, it emits an edit for the inner content of the string, leaving the quotes in place. The same-class check walks the ancestor scopes of the target's definitions, so an unrelated class with a slot of the same name is left alone. Scope for now: same class only, dict keys only, single-part strings.
lerebear
left a comment
There was a problem hiding this comment.
Thank you for the edits: the latest looks good. I made a few minor modifications in preparation for this to merge.
Fixes astral-sh/ty#3674.
When you rename an instance attribute, ty now also renames the matching string in the class's
__slots__. Pylance does this and the issue asks for the same behavior.How it works
The references visitor already walks every node looking for matches. I added a check on string literals: when it hits one, it looks at whether the string is sitting in a
__slots__assignment inside a class body, and whether the attribute being renamed actually belongs to that class. If both hold, it emits an edit for the inner content of the string (the quotes stay put).The same-class check walks the ancestor scopes of the rename target's definitions and looks for the class that owns the
__slots__. So if two unrelated classes both have a"value"slot, renamingself.valueon one of them leaves the other one alone.Scope
This is intentionally a first cut, matching what was discussed on the issue:
__slots__written as a tuple, list, set, or dict literal; for a dict, only the keys are renamed (values are left as-is, which is what was requested)"a" "b"are skipped)Renaming is still driven from the attribute itself. Starting a rename on the
__slots__string directly isn't supported, since a string literal isn't a renameable symbol on its own.Tests
Added rename tests in
ty_idecovering tuple/list/set/dict-key slots, the same-class isolation case, that dict values are not touched, and that starting from the slot string is rejected.cargo test -p ty_ide,cargo clippy -p ty_ide, andcargo fmtall pass.