Lizard Code Analyzer

1.21.3 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `lizard` to analyze a Python file programmatically. It creates a dummy Python file, analyzes it, and prints out key metrics for each function found. It also shows how to analyze a source code string directly.

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}")

view raw JSON →