Xenon Python Code Metrics Tool
Xenon is a Python code complexity tool that analyzes source code for various metrics like cyclomatic complexity, raw LOC, and maintainability index, leveraging the `radon` library. It's designed for integration into CI pipelines to monitor code quality against defined thresholds. The current version is 0.9.3, with updates occurring periodically, often tied to `radon` releases.
Warnings
- breaking Version 0.9.0 introduced significant breaking changes in configuration handling, default file filtering (now only Python files by default), and the JSON report output format.
- gotcha Xenon is primarily a command-line tool. Its Python 'library' usage involves calling `xenon.main.main(args)` directly, which mimics `sys.argv` and can call `sys.exit()` (raising `SystemExit`). It does not provide a high-level, object-oriented API for analysis results.
- gotcha Xenon's default behavior changed in 0.9.0 to only analyze Python files (`*.py`). If you need to analyze other file types (e.g., Jupyter notebooks with `--max-nb-complexity`), you must explicitly specify `--include` or `--pattern`.
Install
-
pip install xenon
Imports
- main
from xenon.main import main
Quickstart
import sys
from io import StringIO
from contextlib import redirect_stdout
from xenon.main import main
# Simulate running xenon from the command line
# This will write output to stdout, so we capture it.
args = [
'--max-complexity', '10',
'--max-blocks', '50',
'.'
]
# Capture stdout to see the results
old_stdout = sys.stdout
redirected_output = StringIO()
sys.stdout = redirected_output
try:
# main() returns 0 for success, non-zero for failure (thresholds exceeded)
result_code = main(args)
output = redirected_output.getvalue()
print("Xenon Analysis Output:")
print(output)
if result_code != 0:
print(f"Xenon found issues (exit code: {result_code}).")
else:
print("Xenon analysis passed all thresholds.")
except SystemExit as e:
# main() uses sys.exit(), which raises SystemExit in Python.
# The exit code is in e.code
output = redirected_output.getvalue()
print("Xenon Analysis Output:")
print(output)
print(f"Xenon exited with code: {e.code}")
finally:
sys.stdout = old_stdout # Restore stdout
# For a real-world scenario, you might run it on a specific file/directory.
# Example: args = ['--max-complexity', '10', 'your_project_dir/your_file.py']