Refactoring the code is the process of changing the structure of a specific variable name inside your code. For example, you may choose a name for your variable and use it for a project that consists of multiple source files, then later decide to rename the variable to something more descriptive. PyCharm provides many refactoring techniques, to make sure that the code can be updated without breaking the operation.
PyCharm does the following:
- The refactoring itself
- Scans every file inside the project and makes sure that the references to the variables are updated
- If something can't be updated automatically, it will give you a warning and open a menu, so you can decide what to do
- Saves the code before refactoring it, so you can revert it later
Let's look at an example. Assume that we have three Python files in our project, called refactor_1.py, refactor_2.py, and refactor_3.py. The first file contains important_funtion(x), which is also used in both refactor_2.py and refactor_3.py.
Copy the following code in a refactor_1.py file:
def important_function(x):
print(x)
Copy the following code in a refactor_2.py file:
from refactor_1 import important_function
important_function(2)
Copy the following code in a refactor_3.py file:
from refactor_1 import important_function
important_function(10)
To perform the refactoring, you need to right-click on the method itself, select Refactor | Rename, and enter the new name for the method:
Notice that a window opens at the bottom of the IDE, listing all references of this function, the current value for each one, and which file will be affected after the refactoring:
If you choose Do Refactor, all of the references will be updated with the new name, and your code will not be broken.