Radon: A Tool to Evaluate Your Code's Style
Despite the rise in low-code platforms, developing chatbots or the systems that support them can require programming. You might need to work with APIs to extend the capabilities of your bot, or you may try to log interactions with users. You’d probably give a lot of thought to a feature and how it works. After the feature is implemented, though, you will need to maintain and update it.
While code may seem clear and intuitive as you work on the feature, it can be challenging to dive back into different parts of the codebase to debug errors or adjust the way things work. Not to mention, team members may have to work with that code later without being as familiar with what it does. In these cases, the clarity and readability of your code is important. There are plenty of tools you might use, from documentation to docstrings, to keep your work clear for your (future) self and others. Radon is a Python package that helps you measure your code complexity.
Radon calculates metrics about code. There are various ways of measuring complexity and maintainability. A function would likely score higher as it became longer. Similarly, a function with more nested if-statements and many conditions would score higher. Radon’s scores can help you evaluate your code. But it isn’t necessary to always try to get a top score for each function. Sometimes, there may be valid reasons to have longer or slightly more complicated blocks of code.
To use it, install the Radon package.
>>> pip install radon
Then, you can run Radon to score your code. `cc` indicates that Radon should measure cyclomatic complexity, but there are other measurement options. `-a` tells Radon we want an average score for the file.
>>> radon cc {file_name} -a
F 7:0 get_author - A
1 blocks (classes, functions, methods) analyzed.
Average complexity: A (2.0)
Radon will output a few things. The first letter is an abbreviation of the type of code block being measured, such as “F” for “function”. The last letter reveals the score from A to F that Radon gave for a given block of code. Each function or class gets its own line and score. However, the `-a` flag ensures the entire file gets an average complexity score, as well.
When developing, you need to consider not only whether your code works but also how maintainable it is. One aspect of maintainability is the style of the code. You want code to be clear for you and for others to work with. Also, simpler code may end up being more reusable because it has a narrower focus and function. Radon can help you evaluate your code. It is a tool to quickly assess where you should consider spending time to improve code quality.