Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor with pyCharm from "user" to "self.user"

I want to move a variable from local scope to object level. The new code should use self.user and not user like before:

class Foo(object):
    def test_foo(self):
        user=User()
        ...
        user.do()

New code should look like:

class Foo(object):
    def test_foo(self):
        self.user=User() # I can remove this line by hand
        ...
        self.user.do()

I tried to refactor>>rename from user to self.user but pyCharm says: "Inserted identifier is not valid"

How can I refactor this with pyCharm?

like image 266
guettli Avatar asked Sep 19 '14 08:09

guettli


People also ask

How do I refactor in Pycharm?

On the main Refactor menu or from the context menu of the selection, choose the desired refactoring or press the corresponding keyboard shortcut (if any). From the main menu, choose Refactor | Refactor This, or press Ctrl+Alt+Shift+T , and then select the desired refactoring from the popup.

How do you refactor variable names in Pycharm?

Press Shift+F6 or from the main menu, select Refactor | Rename. You can perform the rename refactoring in-place or press Shift+F6 again to open the Rename dialog. Enter a new name of the element to enable the Preview and Refactor buttons. You can specify additional options.


1 Answers

What you are trying to do is not a simple rename, but creating a new instance attribute. As such, instead of using Rename you should use Extract > Field menu item. Alternatively you can access this refactoring as Ctrl+Alt+F (this depends on the shortcuts you have chosen. Mine is the default for KDE).

like image 165
Bakuriu Avatar answered Sep 28 '22 06:09

Bakuriu