0
# Data Models
1
2
Core data structures representing analysis results including function information, file statistics, and complexity metrics. These classes provide structured access to all code analysis data.
3
4
## Capabilities
5
6
### Function Information
7
8
Represents detailed information about individual functions with complexity metrics and location data.
9
10
```python { .api }
11
class FunctionInfo(Nesting):
12
"""
13
Represents function information with complexity metrics.
14
15
Attributes:
16
name (str): Function name
17
cyclomatic_complexity (int): McCabe cyclomatic complexity number
18
nloc (int): Number of lines of code without comments
19
token_count (int): Number of tokens in the function
20
parameter_count (int): Number of function parameters
21
parameters (list): List of parameter names extracted from full_parameters
22
length (int): Total lines including comments and blank lines
23
location (str): File path and line number (e.g., "file.py:25")
24
start_line (int): Starting line number of the function
25
end_line (int): Ending line number of the function
26
filename (str): File containing the function
27
long_name (str): Full qualified name with namespace
28
full_parameters (str): Raw parameter list as string
29
fan_in (int): Number of functions calling this function
30
fan_out (int): Number of functions called by this function
31
general_fan_out (int): General fan-out metric
32
max_nesting_depth (int): Maximum nesting depth reached in the function
33
top_nesting_level (int): Top-level nesting information
34
unqualified_name (str): Function name without namespace qualifiers
35
"""
36
37
def add_to_function_name(self, app):
38
"""
39
Appends text to the function name.
40
41
Args:
42
app (str): Text to append to function name
43
"""
44
45
def add_to_long_name(self, app):
46
"""
47
Appends text to the long function name (includes namespace).
48
49
Args:
50
app (str): Text to append to long name
51
"""
52
53
def add_parameter(self, token):
54
"""
55
Adds a parameter to the function's parameter count.
56
57
Args:
58
token (str): Parameter token to add
59
"""
60
```
61
62
### File Information
63
64
Contains comprehensive file-level statistics and the list of functions found in the file.
65
66
```python { .api }
67
class FileInformation:
68
"""
69
Contains file-level statistics and function list.
70
71
Attributes:
72
filename (str): Path to the analyzed file
73
nloc (int): Total lines of code without comments in file
74
function_list (list): List of FunctionInfo objects for functions in file
75
average_nloc (float): Average lines of code per function
76
average_token_count (float): Average token count per function
77
average_cyclomatic_complexity (float): Average cyclomatic complexity per function
78
CCN (int): Total cyclomatic complexity for the file
79
ND (int): Total of maximum nesting depths across all functions in the file
80
token_count (int): Total token count for the file
81
"""
82
83
def functions_average(self, attr_name):
84
"""
85
Calculates average of a function attribute across all functions.
86
87
Args:
88
attr_name (str): Name of the attribute to average
89
90
Returns:
91
float: Average value of the attribute, or 0 if no functions
92
93
Example:
94
avg_complexity = file_info.functions_average('cyclomatic_complexity')
95
avg_params = file_info.functions_average('parameter_count')
96
"""
97
```
98
99
### File Analysis Engine
100
101
Main analysis engine that processes individual files and applies extensions.
102
103
```python { .api }
104
class FileAnalyzer:
105
"""
106
Main file analysis engine with extension support.
107
108
Args:
109
extensions (list): List of extension objects to apply during analysis
110
"""
111
112
def __call__(self, filename):
113
"""
114
Analyzes a single file and returns file information.
115
116
Args:
117
filename (str): Path to file to analyze
118
119
Returns:
120
FileInformation: Analysis results for the file
121
122
Example:
123
analyzer = FileAnalyzer([])
124
file_info = analyzer('src/app.py')
125
print(f"Functions found: {len(file_info.function_list)}")
126
"""
127
128
def analyze_source_code(self, filename, code):
129
"""
130
Analyzes source code string and returns file information.
131
132
Args:
133
filename (str): Filename for the code (used for language detection)
134
code (str): Source code to analyze
135
136
Returns:
137
FileInformation: Analysis results for the code
138
139
Example:
140
analyzer = FileAnalyzer([])
141
code = "def hello():\\n print('world')"
142
file_info = analyzer.analyze_source_code('test.py', code)
143
"""
144
```
145
146
### Nesting Classes
147
148
Classes representing code nesting levels and namespace structures.
149
150
```python { .api }
151
class Nesting:
152
"""
153
Base class representing one level of nesting.
154
155
Attributes:
156
name_in_space (str): Name within the current namespace
157
"""
158
159
class Namespace(Nesting):
160
"""
161
Represents namespace nesting level.
162
163
Args:
164
name (str): Name of the namespace
165
"""
166
167
def __init__(self, name):
168
"""
169
Initialize namespace with given name.
170
171
Args:
172
name (str): Name of the namespace
173
"""
174
175
@property
176
def name_in_space(self):
177
"""
178
Returns the namespace name.
179
180
Returns:
181
str: The namespace name
182
"""
183
```
184
185
### Helper Classes
186
187
Supporting classes for building analysis results and managing nesting state.
188
189
```python { .api }
190
class FileInfoBuilder:
191
"""
192
Builder for file and function information (also called "context").
193
Manages the construction of FileInformation objects during parsing.
194
"""
195
196
class NestingStack:
197
"""
198
Manages nesting stack for code analysis.
199
200
Properties:
201
current_nesting_level (int): Current depth of nesting
202
last_function (FunctionInfo): Most recently processed function
203
"""
204
205
def add_namespace(self, namespace):
206
"""Add a namespace to the nesting stack."""
207
208
def start_new_function_nesting(self, func):
209
"""Start tracking a new function's nesting."""
210
211
def pop_nesting(self):
212
"""Remove the top level of nesting."""
213
214
class OutputScheme:
215
"""
216
Manages output formatting and column schemas.
217
Handles the formatting of analysis results for display.
218
"""
219
220
def function_info_head(self):
221
"""Returns header string for function information display."""
222
223
def function_info(self, func):
224
"""Formats function information for display."""
225
226
class AllResult:
227
"""
228
Aggregates analysis results across all files.
229
Provides summary statistics for entire analysis runs.
230
"""
231
232
def function_count(self):
233
"""Returns total number of functions analyzed."""
234
235
def nloc_in_functions(self):
236
"""Returns total lines of code in all functions."""
237
238
def as_fileinfo(self):
239
"""Returns aggregated data as a FileInformation object."""
240
```
241
242
## Usage Examples
243
244
### Accessing Function Details
245
246
```python
247
import lizard
248
249
results = lizard.analyze(['src/'])
250
for file_info in results:
251
print(f"File: {file_info.filename}")
252
print(f"Total NLOC: {file_info.nloc}")
253
print(f"Number of functions: {len(file_info.function_list)}")
254
255
for func in file_info.function_list:
256
print(f" Function: {func.name}")
257
print(f" Location: {func.location}")
258
print(f" Complexity: {func.cyclomatic_complexity}")
259
print(f" NLOC: {func.nloc}")
260
print(f" Parameters: {func.parameter_count}")
261
print(f" Length: {func.length}")
262
```
263
264
### File-Level Statistics
265
266
```python
267
import lizard
268
269
results = lizard.analyze(['src/'])
270
for file_info in results:
271
print(f"File: {file_info.filename}")
272
print(f" Total complexity: {file_info.CCN}")
273
print(f" Max nesting depth: {file_info.ND}")
274
print(f" Average complexity per function: {file_info.average_cyclomatic_complexity:.2f}")
275
print(f" Average NLOC per function: {file_info.average_nloc:.2f}")
276
print(f" Average tokens per function: {file_info.average_token_count:.2f}")
277
```
278
279
### Direct File Analysis
280
281
```python
282
import lizard
283
284
# Analyze a single file directly
285
analyzer = lizard.FileAnalyzer([])
286
file_info = analyzer('src/complex_module.py')
287
288
print(f"Analyzed: {file_info.filename}")
289
print(f"Functions found: {len(file_info.function_list)}")
290
291
# Find most complex function
292
most_complex = max(file_info.function_list,
293
key=lambda f: f.cyclomatic_complexity)
294
print(f"Most complex function: {most_complex.name} (CCN: {most_complex.cyclomatic_complexity})")
295
```
296
297
### Source Code String Analysis
298
299
```python
300
import lizard
301
302
code = '''
303
def calculate_price(base_price, discount, tax_rate):
304
if discount > 0:
305
if discount > 0.5:
306
final_price = base_price * 0.5
307
else:
308
final_price = base_price * (1 - discount)
309
else:
310
final_price = base_price
311
312
if tax_rate > 0:
313
final_price *= (1 + tax_rate)
314
315
return final_price
316
'''
317
318
analyzer = lizard.FileAnalyzer([])
319
file_info = analyzer.analyze_source_code('example.py', code)
320
321
func = file_info.function_list[0]
322
print(f"Function: {func.name}")
323
print(f"Complexity: {func.cyclomatic_complexity}")
324
print(f"Parameters: {func.parameter_count}")
325
print(f"NLOC: {func.nloc}")
326
```