Lizard Code Analyzer
Lizard is an extensible Cyclomatic Complexity Analyzer for multiple programming languages, including C/C++, Java, JavaScript, Python, Ruby, Swift, and Objective C. It calculates metrics such as cyclomatic complexity number (CCN), lines of code (NLOC), token count, and parameter count. Version 1.21.3 is currently active, with a regular release cadence addressing bug fixes and improvements.
Warnings
- gotcha When running `lizard` from the command line, the tool will exit with a non-zero status code if any warnings are generated (e.g., functions exceeding complexity thresholds). This is intended for CI/CD pipelines but might be unexpected if not accounted for.
- gotcha When using the `--exclude` option (or `-x`) for file exclusion patterns, ensure to wrap patterns with quotation marks (e.g., `-x "./tests/*"`) to prevent shell expansion issues.
- breaking Older versions of `lizard` (e.g., 1.7.x and earlier) supported Python 2.6/2.7/3.x. However, recent versions (like 1.21.3) are built for Python 3.8 and newer. Attempting to install or run the latest `lizard` on older Python 3 versions or Python 2 will result in errors.
- gotcha In C/C++ code, preprocessor directives like `#if` will increase the cyclomatic complexity count by default. This might lead to higher complexity scores than expected if you are not aware of this behavior.
Install
-
pip install lizard
Imports
- lizard
import lizard
Quickstart
import lizard
import os
# Create a dummy Python file for analysis
code_to_analyze = '''
def calculate_something(a, b):
if a > 0:
if b > 0:
return a + b
else:
return a - b
elif a < 0:
return b
else:
return 0
class MyClass:
def __init__(self, val):
self.val = val
def get_val(self):
return self.val
'''
file_path = "example_for_lizard.py"
with open(file_path, "w") as f:
f.write(code_to_analyze)
# Analyze the file
# lizard.analyze_file returns a 'FileInformation' object
file_info = lizard.analyze_file(file_path)
print(f"\n--- Analysis for {file_info.filename} ---")
print(f"Total lines of code (NLOC): {file_info.nloc}")
for func_info in file_info.function_list:
print(f"\n Function: {func_info.name}")
print(f" Cyclomatic Complexity (CCN): {func_info.cyclomatic_complexity}")
print(f" NLOC: {func_info.nloc}")
print(f" Parameter Count: {func_info.parameters}")
print(f" Token Count: {func_info.token_count}")
# Clean up the dummy file
os.remove(file_path)
# Example of analyzing a string directly (requires a filename hint for language detection)
string_code = "def simple_func():\n pass"
string_info = lizard.analyze_source_code("temp.py", string_code)
print(f"\n--- Analysis for string code (temp.py) ---")
for func_info in string_info.function_list:
print(f" Function: {func_info.name}, CCN: {func_info.cyclomatic_complexity}")