LocalToField doesn't validate the offset until get_changes()

Open Beginner friendly
#927 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 7 days

Nobody has claimed this yet.

Assessment

Difficulty
1/5
Estimated time
1-3 hours
Newbie friendliness
88/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
devtools

Research direction

The offset check lives in _is_a_method_local(), called from get_changes() in rope/refactor/localtofield.py; the other refactorings in rope/refactor do this check in __init__, so compare with them. Run the reproduction snippet from the issue to see the error arrive late. Done when the constructor raises RefactoringError for a module-level variable and a test in the existing localtofield test module covers it.

Written by the indexing model from the issue text.

Description

Most refactorings check their offset in the constructor and raise RefactoringError straight away: Rename, create_inline(), MethodObject, IntroduceParameter and UseFunction all do. LocalToField only stores its arguments, so the check happens in get_changes().

Editor integrations build the refactoring object to decide whether to offer it in a menu, and only compute the changes when the user picks it. With LocalToField that shortcut doesn't work: building the object always succeeds, so "Convert local variable to field" is offered everywhere. pylsp-rope offers it this way.

To Reproduce

import pathlib
import tempfile

from rope.base.project import Project
from rope.refactor.localtofield import LocalToField

root = pathlib.Path(tempfile.mkdtemp())
(root / "m.py").write_text("x = 1\n")
project = Project(str(root), ropefolder=None)
refactoring = LocalToField(project, project.get_resource("m.py"), 0)
print("constructor accepted a module-level variable")
refactoring.get_changes()

Output on master (46ebf37), Python 3.13:

constructor accepted a module-level variable
rope.base.exceptions.RefactoringError: Convert local variable to field should be performed on a local variable of a method.

Expected behaviour

The constructor raises the RefactoringError. Moving the _is_a_method_local() check from get_changes() into __init__() would do it, and the check is cheap. I can send a PR with a test if that's acceptable.

Editor information

Dominant language
Python
Stars
2.2k
Forks
197
Avg merge
2d 13h
Merged PRs (30d)
5

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-rope/rope

All issues in python-rope/rope

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.