Search code examples
pythonpropertiesrefactoringpycharmautomated-refactoring

Refactor class method to property using Pycharm


I have the following class:

class Dogs(object):
    def __init__(self):
        self.names = []
        self.breeds = set()

    def number(self):
        return len(self.names)

I want to change number to being a property. This means I also want to change all of it usages. Does PyCharm have this built into it's refactoring tools? It seems to be according to this issue.

At this point, I'm doing "find all usages" and then manually fixing each instance. If there isn't a specific refactoring tool for changing a method to a property, is there some way to use "find all usages" more effectively?


Solution

  • Yes, you can refactor a method to a property in PyCharm. Strangely, this does not correspond to any entry in the "Refactor" menu.

    Just place the editor cursor on the name of the method and press Alt+ shortcut to show the available Intentions.

    Then, select "Convert method to property".

    "Convert method to property" intention

    You can also trigger the global action search with Ctrl+Shift+A and select the intention from there.

    Alternative