Home Python Course Menu Book

Python: Refactoring Code


In our new Multiverse class from the previous lesson, we have a method that's poorly named. It's called convert_superhero_name. That was fine when the class was only about superheroes. But now the supervillain class also needs to convert a name to proper/title case. We can simply rename the method by hand, and then go through our code making the necessary changes. But you don't have to do that. PyCharm can do it all for you via something called refactoring.

Refactoring is making changes to your code to make it leaner, meaner, and more efficient. It's quite a large topic, so we'll just concentrate on the renaming aspect of refactoring. We'll change the name of the method convert_superhero_name. We'll call it convert_to_propercase.

Make sure you are in your Multiverse file. Locate the convert_superhero_name method and click somewhere in the name so that it is highlighted:

Refactor Python code

Now right-click. You should see a menu appear. Select Refactor > Rename:

The Refactor > Rename menu in PyCharm

When you select Rename, you'll see a dialog box appear. This one:

The rename dialog box in PyCharm

Check the boxes if you want to search for your method name in comments, strings and text.

Type in a new name and you should see the Refactor and Preview buttons become available:

Rename method dialog box

Click on the Preview button. You should see the following appear at the bottom of the PyCharm window:

Previewing the Python refactor

Expand the section that begins References in code … You'll see this:

The usages of the renamed code

PyCharm has searched through all the files in our project and found 3 usages where the renaming could take place. To accept this, click the Do Refactor button in the bottom left. Your method and its usages will be renamed.

Now have a look at the method in the Multiverse file. It has been changed to convert_to_propercase:

A refactored Python method

Switch to your MainFile code and you'll see the changes have been made there:

Python code that has been refactored

We'll leave classes there. In the next section, we'll have a look at how to connect to a database from Python.