From Clutter to Clarity: Refactor Your Python Code With A Single Command
Code refactoring made easy
Motivation
Writing clean and elegant codebases is an underrated Programming skill. Many programmers, especially newbies, just focus on getting their fundamentals right.
However, only a handful keep an eye on readability and maintainability, as they assume that they are the only ones who will ever use the code.
It’s only when they eventually transition to collaborative projects where, after months (if not years) of messy and inelegant programming habits, one has to adapt to the “correct” methods of programming.
Code refactoring is an essential part of the software development process, but it’s often overlooked or neglected.
In fact, the Zen of Python says:
If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea.
While it is understandable that code refactoring is not an activity that one looks forward to, however, it is important for a variety of reasons. For instance, you can keep your codebase clean and well-organized over time, saving you time and effort in the long run.
To make things easier, wouldn’t it be nice to have a tool that could highlight potential areas of refactoring for us to review manually?
Therefore, in this blog, I will demonstrate how you can refactor code using Sourcery — an automatic code refactoring tool that makes your code clearer, concise, and Pythonic.
Let’s begin 🚀!
Installation and Setup
You can leverage Sourcery as an IDE plugin in VS Code and PyCharm, Command-Line Interface (CLI), Sublime Text, Vim, GitHub, and a few more.
For this blog, we shall focus on using Sourcery in an IDE and CLI specifically.
Command Line
You can install Sourcery’s command line interface by running the following command:
pip install sourcery-cli
After installation, you need to log in with this command:
sourcery login
After login, you will see a similar response in your terminal:
Visual Studio Code IDE
You can leverage Sourcery in VS Code by installing its extension. These are the steps:
Code Refactoring in CLI
Next, let’s look at a few demos of how you can refactor code using Sourcery in CLI.
Here, we shall write some code snippets in a script, refactor it using Sourcery and review the suggestions.
Code Refactoring Demo #1
Consider we have a file my_code.py
:
## my_code.py
def find_even(numbers):
even_numbers = []
for num in numbers:
if num%2 == 0:
even_numbers.append(num)
print(even_numbers)
To refactor, run the following command:
sourcery review --in-place my_code.py
With this, Sourcery’s AI refactoring transforms our code to:
## my_code.py
def find_even(numbers):
even_numbers = [num for num in numbers if num%2 == 0]
print(even_numbers)
The suggested change is accurate, concise and elegant.
Code Refactoring Demo #2
Consider now our file my_code.py
has the following code:
# my_code.py
def is_special_number(number):
if number == 7:
return True
elif number == 18:
return True
else:
return False
To refactor, run the following command:
sourcery review --in-place my_code.py
This time, we see the following changes in the file:
# my_code.py
def is_special_number(number):
return number in [7, 18]
This is, yet again, correct and clean.
Code Refactoring Demo #3
Let’s consider an example of nested if statements:
## my_code.py
def check_numbers(number1, number2):
if number1:
if number2:
return True
return False
Next, we run the following command:
sourcery review --in-place my_code.py
Sourcery suggests the following changes to the file:
## my_code.py
def check_numbers(number1, number2):
return bool(number1 and number2)
This is indeed correct and more elegant than before.
Code Refactoring Demo #4
Next, we have a for-loop which finds if the input list of numbers has a positive integer or not.
## my_code.py
def has_positive(numbers):
for number in numbers:
if number>0:
return True
return False
The ideal way to do this is to use any()
in Python. Let’s see if Sourcery can detect that.
We run the following command:
sourcery review --in-place my_code.py
Sourcery suggests the following changes to the file:
def has_positive(numbers):
return any(number>0 for number in numbers)
Super Impressive!
Code Refactoring Demo #5
Next, we have an if-condition that assigns a value to a variable my_var
based on the condition
## my_code.py
def set_variable(condition):
if condition:
my_var = 1
else:
my_var = 2
return my_var
The ideal way to do this is to use an if-expression in Python. Let’s see if Sourcery suggests that.
To refactor, we run the following command:
sourcery review --in-place my_code.py
Sourcery suggests the following changes to the file:
def set_variable(condition):
return 1 if condition else 2
Code Refactoring in IDE
Next, let’s look at we can refactor code in VS Code.
For this demonstration, I have transferred the five code refactoring demonstrations above in a script opened in VS Code.
Once we toggle the panel, we see the refactoring suggestions by Sourcery. This is shown below:
Once we hover over a suggestion in the panel and click the warning ⚠️ sign, we see three options, as shown below:
The first option refactors the code. Second skips the suggestion. The final option will never show the suggested refactoring across any file.
After selecting the first option, Sourcery will refactor the code. This is shown below:
Conclusion
Congratulations on taking a step toward writing cleaner code, which will go a long way in your programming career.
Code refactoring is an essential part of an end-to-end software development process that can significantly improve the quality and maintainability of your codebase, where tools like Sourcery can immensely help.
Moreover, at times, one may want to refactor the code according to their own guidelines. Thankfully, with Sourcery, you can provide custom rules for personalized refactoring.
You can read more about Sourcery here.
If you want to learn more such elegant tools, tips and tricks about Data Science and Python, I post an informative tip daily on LinkedIn.
You can find all the tips I have posted in My LinkedIn Post Archive. You can follow me on LinkedIn to see all future posts.
Alternatively, you can also receive them via email by subscribing below:
Thanks for reading!