Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a variable in a Python code in MS VS Code

I have defined a variable T_0 at the top of a python code, and want to change this variable by F2 of MS VS Code.

T_0 = 10
T_1 = T_0 + 1
print(T_1)

But first, I got an error message Refactoring library rope is not installed.

Then I found an answer to this at here. After appropriately changed this, I got a new error message Refactor failed. Rename refactoring should be performed on resolvable python identifiers..

How can I rename a variable in a python code on MS VS Code?

I am using Python 3.6, VS Code 1.19.2.

like image 228
ysBach Avatar asked Jan 24 '18 09:01

ysBach


3 Answers

I had the same problem. I tried several solutions and solved it. However I didn't know which one worked actually. You can refer my methods but they may not work for you.

  1. I found there were two rope packages installed in my conda environment (python3.6), one for python3.6 and another for python2.7. In fact, after I uninstalled one rope package, I found it still existed with another version number. It was really strange. So I uninstalled them all and re-installed it with conda (or pip).
  2. The extensions python and Visual Studio IntelliCode may be not compatible. Because auto-completion didn't work for me and it worked again after I uninstalled the latter.
  3. Re-install vscode and all its extensions completely.
like image 45
Kani Avatar answered Sep 23 '22 17:09

Kani


It is confirmed as a problem with rope 0.10.7

This link shows how this error is connected to rope https://github.com/Microsoft/vscode-python/issues/2094

and this link shows that the issue with rope is still unresolved as of 2020 April 2 https://github.com/python-rope/rope/issues/249

like image 55
Ben Avatar answered Sep 24 '22 17:09

Ben


This is not a fix for the bug mentioned in Ben's answer, but it did fix the issue for my project and configuration:

  • Visual Studio Code 1.51.1
  • Python 3.8.5
  • rope 0.18.0
  • venv

The issue was not with my project's code but code inside the .venv subdirectory that rope also tried to examine. There is a config file for rope in vscode, located at .vscode/.ropeproject/config.py in my case, and inside:

def set_prefs(prefs):
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
                                  '.hg', '.svn', '_svn', '.git', '.tox']

Adding '.venv' to the array made rope skip that directory and rename refactor started working. Admittedly, there were still cases I found where it would not catch uses of a name and failed to rename things without warning, which leads me to not trust the function.

like image 45
tychon Avatar answered Sep 25 '22 17:09

tychon