Welcome to Radon’s documentation!

Travis-CI badge Coveralls badge PyPI latest version badge PyPI downloads badge Download format Radon license

Radon is a Python tool which computes various code metrics. Supported metrics are:

  • raw metrics: SLOC, comment lines, blank lines, &c.
  • Cyclomatic Complexity (i.e. McCabe’s Complexity)
  • Halstead metrics (all of them)
  • the Maintainability Index (a Visual Studio metric)

Radon can be used either from the command line or programmatically through its API.

Contents:

Introduction to Code Metrics

This section contains a brief explanations of the metrics that Radon can compute.

Cyclomatic Complexity

Cyclomatic Complexity corresponds to the number of decisions a block of code contains plus 1. This number (also called McCabe number) is equal to the number of linearly independent paths through the code. This number can be used as a guide when testing conditional logic in blocks.

Radon analyzes the AST tree of a Python program to compute Cyclomatic Complexity. Statements have the following effects on Cyclomatic Complexity:

Construct Effect on CC Reasoning
if +1 An if statement is a single decision.
elif +1 The elif statement adds another decision.
else +0 The else statement does not cause a new decision. The decision is at the if.
for +1 There is a decision at the start of the loop.
while +1 There is a decision at the while statement.
except +1 Each except branch adds a new conditional path of execution.
finally +0 The finally block is unconditionally executed.
with +1 The with statement roughly corresponds to a try/except block (see PEP 343 for details).
assert +1 The assert statement internally roughly equals a conditional statement.
Comprehension +1 A list/set/dict comprehension of generator expression is equivalent to a for loop.
Boolean Operator +1 Every boolean operator (and, or) adds a decision point.

Maintainability Index

Maintainability Index is a software metric which measures how maintainable (easy to support and change) the source code is. The maintainability index is calculated as a factored formula consisting of SLOC (Source Lines Of Code), Cyclomatic Complexity and Halstead volume. It is used in several automated software metric tools, including the Microsoft Visual Studio 2010 development environment, which uses a shifted scale (0 to 100) derivative.

Common formulas are:

  • the original formula:

    \[MI = 171 - 5.2 \ln V - 0.23 G - 16.2 \ln L\]
  • the derivative used by SEI:

    \[MI = 171 - 5.2\log_2 V - 0.23 G - 16.2 \log_2 L + 50 \sin(\sqrt{2.4 C})\]
  • the derivative used by Visual Studio:

    \[MI = \max \left [ 0, 100\dfrac{171 - 5.2\ln V - 0.23 G - 16.2 \ln L}{171} \right ].\]

Radon uses another derivative, computed from both SEI derivative and Visual Studio one:

\[MI = \max \left [ 0, 100\dfrac{171 - 5.2\ln V - 0.23 G - 16.2 \ln L + 50 \sin(\sqrt{2.4 C}))}{171} \right ]\]
Where:
  • V is the Halstead Volume (see below);
  • G is the total Cyclomatic Complexity;
  • L is the number of Source Lines of Code (SLOC);
  • C is the percent of comment lines (important: converted to radians).

Note

Maintainability Index is still a very experimental metric, and should not be taken into account as seriously as the other metrics.

Raw Metrics

The following are the definitions employed by Radon:

  • LOC: The total number of lines of code. It does not necessarily correspond to the number of lines in the file.
  • LLOC: The number of logical lines of code. Every logical line of code contains exactly one statement.
  • SLOC: The number of source lines of code - not necessarily corresponding to the LLOC.
  • Comments: The number of comment lines. Multi-line strings are not counted as comment since, to the Python interpreter, they are just strings.
  • Multi: The number of lines which represent multi-line strings.
  • Blanks: The number of blank lines (or whitespace-only ones).

The equation SLOC + Multi + Single comments + Blank = LOC should always hold. Additionally, comment stats are calculated:

  • C % L: the ratio between number of comment lines and LOC, expressed as a percentage;
  • C % S: the ratio between number of comment lines and SLOC, expressed as a percentage;
  • C + M % L: the ratio between number of comment and multiline strings lines and LOC, expressed as a percentage.

Halstead Metrics

Halstead’s goal was to identify measurable properties of software, and the relations between them. These numbers are statically computed from the source code:

  • \(\eta_1\) = the number of distinct operators
  • \(\eta_2\) = the number of distinct operands
  • \(N_1\) = the total number of operators
  • \(N_2\) = the total number of operands

From these numbers several measures can be calculated:

  • Program vocabulary: \(\eta = \eta_1 + \eta_2\)
  • Program length: \(N = N_1 + N_2\)
  • Calculated program length: \(\widehat{N} = \eta_1 \log_2 \eta_1 + \eta_2 \log_2 \eta_2\)
  • Volume: \(V = N \log_2 \eta\)
  • Difficulty: \(D = \dfrac{\eta_1}{2} \cdot \dfrac{N_2}{\eta_2}\)
  • Effort: \(E = D \cdot V\)
  • Time required to program: \(T = \dfrac{E}{18}\) seconds
  • Number of delivered bugs: \(B = \dfrac{V}{3000}\).

Further Reading

  1. Paul Omand and Jack Hagemeister. “Metrics for assessing a software system’s maintainability”. Proceedings International Conference on Software Mainatenance (ICSM), 1992. (doi)
  2. Don M. Coleman, Dan Ash, Bruce Lowther, Paul W. Oman. Using Metrics to Evaluate Software System Maintainability. IEEE Computer 27(8), 1994. (doi, postprint)
  3. Maintainability Index Range and Meaning. Code Analysis Team Blog, blogs.msdn, 20 November 2007.
  4. Arie van Deursen, Think Twice Before Using the “Maintainability Index”.

Command-line Usage

Radon currently has four commands:

  • cc: compute Cyclomatic Complexity
  • raw: compute raw metrics
  • mi: compute Maintainability Index
  • hal: compute Halstead complexity metrics

Note

On some systems, such as Windows, the default encoding is not UTF-8. If you are using Unicode characters in your Python file and want to analyze it with Radon, you’ll have to set the RADONFILESENCODING environment variable to UTF-8.

Radon configuration files

When using radon regularly, you may want to specify default argument values in a configuration file. For example, all of the radon commands have a --exclude and --ignore argument on the command-line.

Radon will look for the following files to determine default arguments:

  • radon.cfg
  • setup.cfg
  • ~/.radon.cfg

Any radon configuration will be given in the INI-format, under the section [radon].

For example:

[radon]
exclude = test_*.py
cc_min = B

Usage with Jupyter Notebooks

Radon can be used with .ipynb files to inspect code metrics for Python cells. Any % macros will be ignored in the metrics.

Note

Jupyter Notebook support requires the optional nbformat package. To install, run pip install nbformat.

To enable scanning of Jupyter notebooks, add the --include-ipynb flag with any of the commands.

To enable reporting of individual cells, add the --ipynb-cells flag with any of the commands.

The cc command

This command analyzes Python source files and compute Cyclomatic Complexity. The output can be filtered by specifying the -n and -x flags. By default, the complexity score is not displayed, the option -s (show complexity) toggles this behaviour. File or directories exclusion is supported through glob patterns. Every positional argument is interpreted as a path. The program then walks through its children and analyzes Python files. Every block will be ranked from A (best complexity score) to F (worst one). Ranks corresponds to complexity scores as follows:

CC score Rank Risk
1 - 5 A low - simple block
6 - 10 B low - well structured and stable block
11 - 20 C moderate - slightly complex block
21 - 30 D more than moderate - more complex block
31 - 40 E high - complex block, alarming
41+ F very high - error-prone, unstable block

Blocks are also classified into three types: functions, methods and classes. They’re listed by letter in the command output for convenience when scanning through a longer list of blocks:

Block type Letter
Function F
Method M
Class C

Options

-x, --max

Set the maximum complexity rank to display, defaults to F.

Value can be set in a configuration file using the cc_max property.

-n, --min

Set the minimum complexity rank to display, defaults to A.

Value can be set in a configuration file using the cc_min property.

-a, --average

If given, at the end of the analysis show the average Cyclomatic Complexity. This option is influenced by -x, --max and -n, --min options.

Value can be set in a configuration file using the average property.

--total-average

Like -a, --average, but it is not influenced by min and max. Every analyzed block is counted, no matter whether it is displayed or not.

Value can be set in a configuration file using the total_average property.

-s, --show-complexity

If given, show the complexity score along with its rank.

Value can be set in a configuration file using the show_complexity property.

-e, --exclude

Exclude files only when their path matches one of these glob patterns. Usually needs quoting at the command line.

Value can be set in a configuration file using the exclude property.

-i, --ignore

Ignore directories when their name matches one of these glob patterns: radon won’t even descend into them. By default, hidden directories (starting with ‘.’) are ignored.

Value can be set in a configuration file using the ignore property.

-o, --order

The ordering function for the results. Can be one of:

  • SCORE: order by cyclomatic complexity (descending):
  • LINES: order by line numbers;
  • ALPHA: order by block names (alphabetically).

Value can be set in a configuration file using the order property.

-j, --json

If given, the results will be converted into JSON. This is useful in case you need to export the results to another application.

--xml

If given, the results will be converted into XML. Note that not all the information is kept. This is specifically targeted to Jenkin’s plugin CCM.

--no-assert

Does not count assert statements when computing complexity. This is because Python can be run with an optimize flag which removes assert statements.

Value can be set in a configuration file using the no_assert property.

--include-ipynb

Include the Python cells within IPython Notebooks in the reporting.

Value can be set in a configuration file using the include_ipynb property.

--ipynb-cells

Report on individual cells in any .ipynb files.

Value can be set in a configuration file using the ipynb_cells property.

-O, --output-file

Save output to the specified output file.

Value can be set in a configuration file using the output_file property.

Examples

$ radon cc path

Radon will walk through the subdirectories of path and will analyze all child nodes (every Python file it encounters).

$ radon cc -e "path/tests*,path/docs/*" path

As in the above example, Radon will walk the directories, excluding paths matching path/tests/* and path/docs/*.

Warning

Remember to quote the patterns, otherwise your shell might expand them!

Depending on the single cases, a more suitable alternative might be this:

$ radon cc -i "docs,tests" path
$ cat path/to/file.py | radon cc -

Setting the path to “-” will cause Radon to analyze code from stdin

$ radon cc --min B --max E path

Here Radon will only display blocks ranked between B and E (i.e. from CC=6 to CC=40).

The mi command

This command analyzes Python source code files and compute the Maintainability Index score. Every positional argument is treated as a starting point from which to walk looking for Python files (as in the cc command). Paths can be excluded with the -e option. The Maintainability Index is always in the range 0-100. MI is ranked as follows:

MI score Rank Maintainability
100 - 20 A Very high
19 - 10 B Medium
9 - 0 C Extremely low

Options

-x, --max

Set the maximum MI to display. Expects a letter between A-F. Defaults to C.

Value can be set in a configuration file using the mi_max property.

-n, --min

Set the minimum MI to display. Expects a letter between A-F. Defaults to A.

Value can be set in a configuration file using the mi_min property.

-e, --exclude

Exclude files only when their path matches one of these glob patterns. Usually needs quoting at the command line.

Value can be set in a configuration file using the exclude property.

-i, --ignore

Ignore directories when their name matches one of these glob patterns: radon won’t even descend into them. By default, hidden directories (starting with ‘.’) are ignored.

Value can be set in a configuration file using the ignore property.

-m, --multi

If given, Radon will not count multiline strings as comments. Most of the time this is safe since multiline strings are used as functions docstrings, but one should be aware that their use is not limited to that and sometimes it would be wrong to count them as comment lines.

Value can be set in a configuration file using the multi property.

-s, --show

If given, the actual MI value is shown in results, alongside the rank.

Value can be set in a configuration file using the show_mi property.

-j, --json

Format results in JSON.

--include-ipynb

Include the Python cells within IPython Notebooks in the reporting.

Value can be set in a configuration file using the include_ipynb property.

--ipynb-cells

Report on individual cells in any .ipynb files.

Value can be set in a configuration file using the ipynb_cells property.

-O, --output-file

Save output to the specified output file.

Value can be set in a configuration file using the output_file property.

Examples

$ radon mi path1 path2

Analyze every Python file under path1 or path2. It checks recursively in every subdirectory.

$ radon mi path1 -e "path1/tests/*"

Like the previous example, but excluding from the analysis every path that matches path1/tests/*.

$ radon mi -m path1

Like the previous examples, but does not count multiline strings as comments.

The raw command

This command analyzes the given Python modules in order to compute raw metrics. These include:

  • LOC: the total number of lines of code
  • LLOC: the number of logical lines of code
  • SLOC: the number of source lines of code - not necessarily corresponding to the LLOC [Wikipedia]
  • comments: the number of Python comment lines (i.e. only single-line comments #)
  • multi: the number of lines representing multi-line strings
  • blank: the number of blank lines (or whitespace-only ones)

The equation \(sloc + multi + single comments + blank = loc\) should always hold.

[Wikipedia]More information on LOC, SLOC, LLOC here: http://en.wikipedia.org/wiki/Source_lines_of_code

Options

-e, --exclude

Exclude files only when their path matches one of these glob patterns. Usually needs quoting at the command line.

Value can be set in a configuration file using the exclude property.

-i, --ignore

Ignore directories when their name matches one of these glob patterns: radon won’t even descend into them. By default, hidden directories (starting with ‘.’) are ignored.

Value can be set in a configuration file using the ignore property.

-s, --summary

If given, at the end of the analysis a summary of the gathered metrics will be shown.

-j, --json

If given, the results will be converted into JSON.

-O, --output-file

Save output to the specified output file.

Value can be set in a configuration file using the output_file property.

--include-ipynb

Include the Python cells within IPython Notebooks in the reporting.

Value can be set in a configuration file using the include_ipynb property.

--ipynb-cells

Report on individual cells in any .ipynb files.

Value can be set in a configuration file using the ipynb_cells property.

Examples

$ radon raw path1 path2

Analyze every Python file under path1 or path2. It checks recursively in every subdirectory.

$ radon raw path1 -e "path1/tests/*"

Like the previous example, but excluding from the analysis every path that matches path1/tests/*.

The hal command

This command analyzes Python source files and computes their Halstead complexity metrics. Files can be analyzed as wholes, or in terms of their top-level functions with the -f flag.

Excluding files or directories is supported through glob patterns with the -e flag. Every positional argument is interpreted as a path. The program walks through its children and analyzes Python files.

Options

-f, --functions

Compute the metrics on the function level, as opposed to the file level.

Value can be set in a configuration file using the functions property.

-e, --exclude

Exclude files when their path matches one of these glob patterns. Usually needs quoting at the command line.

Value can be set in a configuration file using the exclude property.

-i, --ignore

Refuse to descend into directories that match any of these glob patterns. By default, hidden directories (starting with ‘.’) are ignored.

Value can be set in a configuration file using the ignore property.

-j, --json

Convert results into JSON. This is useful for exporting results to another application.

-O, --output-file

Save output to the specified output file.

Value can be set in a configuration file using the output_file property.

--include-ipynb

Include the Python cells within IPython Notebooks in the reporting.

Value can be set in a configuration file using the include_ipynb property.

--ipynb-cells

Report on individual cells in any .ipynb files.

Value can be set in a configuration file using the ipynb_cells property.

Examples

$ radon hal file.py

Radon will analyze the given file.

$ radon hal path/

Radon will walk through the subdirectories of path/ and analyze all child nodes (every Python file it encounters).

$ radon hal -e 'path/tests*,path/docs/*' path/

As in the above example, Radon will walk the directories, excluding paths matching path/tests/* and path/docs/*.

Warning

Remember to quote the patterns, otherwise your shell might expand them!

Depending on the single cases, a more suitable alternative might be this:

$ radon hal -i "docs,tests" path
$ radon hal - < path/to/file.py

Setting the path to “-” will cause Radon to analyze code from stdin.

Flake8 plugin

Radon exposes a plugin for the Flake8 tool. In order to use it you will have to install both radon and flake8.

To enable the Radon checker, you will have to supply at least one of the following options:

--radon-max-cc <int>

Set the cyclomatic complexity threshold. The default value is 10. Blocks with a greater complexity will be reported by the tool.

--radon-no-assert

Instruct radon not to count assert statements towards cyclomatic complexity. The default behaviour is the opposite.

--radon-show-closures

Instruct radon to add closures/inner classes to the output.

For more information visit the Flake8 documentation.

Using radon programmatically

Radon has a set of functions and classes that you can call from within your program to analyze files.

Radon’s API is composed of three layers:

  • at the very bottom (the lowest level) there are the Visitors: with these classes one can build an AST out of the code and get basic metrics. Currently, there are two available visitors: ComplexityVisitor and HalsteadVisitor. With the former one analyzes the cyclomatic complexity of the code, while the latter gathers the so-called Halstead metrics. With those and other raw metrics one can compute the Maintainability Index. Example:

    >>> from radon.visitors import ComplexityVisitor
    >>> v = ComplexityVisitor.from_code('''
    def factorial(n):
        if n < 2: return 1
        return n * factorial(n - 1)
    
    def foo(bar):
        return sum(i for i in range(bar ** 2) if bar % i)
    ''')
    >>> v.functions
    [Function(name='factorial', lineno=2, col_offset=0, endline=4, is_method=False,
    classname=None, closures=[], complexity=2),
    Function(name='foo', lineno=6, col_offset=0, endline=7, is_method=False, classname=None,
    closures=[], complexity=3)]
    
  • at a higher level, there are helper functions residing in separate modules. For cyclomatic complexity, one can use those inside radon.complexity. For Halstead metrics and MI index those inside radon.metrics. Finally, for raw metrics (that includes SLOC, LLOC, LOC, &c.) one can use the function analyze() inside the radon.raw module. With the majority of these functions the result is an object (Module object in the case of raw metrics) or a list of objects (Function or Class objects for cyclomatic complexity). Example:

    >>> from radon.complexity import cc_rank, cc_visit
    >>> cc_rank(4), cc_rank(9), cc_rank(14), cc_rank(23)
    ('A', 'B', 'C', 'D')
    >>> cc_visit('''
    class A(object):
        def meth(self):
            return sum(i for i in range(10) if i - 2 < 5)
    
    def fib(n):
        if n < 2: return 1
        return fib(n - 1) + fib(n - 2)
    ''')
    
    [Function(name='fib', lineno=6, col_offset=0, endline=8, is_method=False, classname=None,
    closures=[], complexity=2), Class(name='A', lineno=2, col_offset=0, endline=4,
    methods=[Function(name='meth', lineno=3, col_offset=4, endline=4, is_method=True,
    classname='A', closures=[], complexity=3)], real_complexity=3),
    Function(name='meth', lineno=3, col_offset=4, endline=4, is_method=True, classname='A',
    closures=[], complexity=3)]
    
    >>> from radon.raw import analyze
    >>> analyze("""def _split_tokens(tokens, token, value):
        '''Split a list of tokens on the specified token pair (token, value),
        where *token* is the token type (i.e. its code) and *value* its actual
        value in the code.
        '''
        res = [[]]
        for token_values in tokens:
            if (token, value) == token_values[:2]:
                res.append([])
                continue
            res[-1].append(token_values)
        return res
    """)
    >>> Module(loc=12, lloc=9, sloc=12, comments=0, multi=4, blank=0)
    
  • at the highest level there are the Harvesters. A Harvester implements all the business logic of the CLI interface. To use a Harvester, it’s sufficient to create a Config object (which contains all the config values) and pass it to the Harvester instance along with a list of paths to analyze. An Harvester can then export its result to various formats (for cyclomatic complexity both JSON and XML are available). It’s possible to find an example for this in the Xenon project.

Cyclomatic Complexity

radon.complexity.cc_visit(code, **kwargs)

Visit the given code with ComplexityVisitor. All the keyword arguments are directly passed to the visitor.

radon.complexity.cc_visit_ast(ast_node, **kwargs)

Visit the AST node with ComplexityVisitor. All the keyword arguments are directly passed to the visitor.

radon.complexity.cc_rank(cc)

Rank the complexity score from A to F, where A stands for the simplest and best score and F the most complex and worst one:

1 - 5 A (low risk - simple block)
6 - 10 B (low risk - well structured and stable block)
11 - 20 C (moderate risk - slightly complex block)
21 - 30 D (more than moderate risk - more complex block)
31 - 40 E (high risk - complex block, alarming)
41+ F (very high risk - error-prone, unstable block)

Here block is used in place of function, method or class.

The formula used to convert the score into an index is the following:

\[\text{rank} = \left \lceil \dfrac{\text{score}}{10} \right \rceil - H(5 - \text{score})\]

where H(s) stands for the Heaviside Step Function. The rank is then associated to a letter (0 = A, 5 = F).

radon.complexity.sorted_results(blocks, order=SCORE)

Given a ComplexityVisitor instance, returns a list of sorted blocks with respect to complexity. A block is a either Function object or a Class object. The blocks are sorted in descending order from the block with the highest complexity.

The optional order parameter indicates how to sort the blocks. It can be:

  • LINES: sort by line numbering;
  • ALPHA: sort by name (from A to Z);
  • SCORE: sorty by score (descending).

Default is SCORE.

Raw metrics

radon.raw.analyze(source)

Analyze the source code and return a namedtuple with the following fields:

  • loc: The number of lines of code (total)
  • lloc: The number of logical lines of code
  • sloc: The number of source lines of code (not necessarily
    corresponding to the LLOC)
  • comments: The number of Python comment lines
  • multi: The number of lines which represent multi-line strings
  • single_comments: The number of lines which are just comments with
    no code
  • blank: The number of blank lines (or whitespace-only ones)

The equation \(sloc + blanks + multi + single_comments = loc\) should always hold. Multiline strings are not counted as comments, since, to the Python interpreter, they are not comments but strings.

Other metrics

radon.metrics.h_visit(code)

Compile the code into an AST tree and then pass it to h_visit_ast().

radon.metrics.h_visit_ast(ast_node)

Visit the AST node using the HalsteadVisitor visitor. The results are HalsteadReport namedtuples with the following fields:

  • h1: the number of distinct operators
  • h2: the number of distinct operands
  • N1: the total number of operators
  • N2: the total number of operands
  • h: the vocabulary, i.e. h1 + h2
  • N: the length, i.e. N1 + N2
  • calculated_length: h1 * log2(h1) + h2 * log2(h2)
  • volume: V = N * log2(h)
  • difficulty: D = h1 / 2 * N2 / h2
  • effort: E = D * V
  • time: T = E / 18 seconds
  • bugs: B = V / 3000 - an estimate of the errors in the implementation

The actual return of this function is a namedtuple with the following fields:

  • total: a HalsteadReport namedtuple for the entire scanned file
  • functions: a list of `HalsteadReport`s for each toplevel function

Nested functions are not tracked.

radon.metrics.mi_visit(code, multi)

Visit the code and compute the Maintainability Index (MI) from it.

radon.metrics.mi_rank(score)

Rank the score with a letter:

  • A if \(\text{score} > 19\);
  • B if \(9 < \text{score} \le 19\);
  • C if \(\text{score} \le 9\).
radon.metrics.mi_parameters(code, count_multi=True)

Given a source code snippet, compute the necessary parameters to compute the Maintainability Index metric. These include:

  • the Halstead Volume
  • the Cyclomatic Complexity
  • the number of LLOC (Logical Lines of Code)
  • the percent of lines of comment
Parameters:multi – If True, then count multiline strings as comment lines as well. This is not always safe because Python multiline strings are not always docstrings.
radon.metrics.mi_compute(halstead_volume, complexity, sloc, comments)

Compute the Maintainability Index (MI) given the Halstead Volume, the Cyclomatic Complexity, the SLOC number and the number of comment lines. Usually it is not used directly but instead mi_visit() is preferred.

Visitors

class radon.visitors.ComplexityVisitor(to_method=False, classname=None, off=True, no_assert=False)

A visitor that keeps track of the cyclomatic complexity of the elements.

Parameters:
  • to_method – If True, every function is treated as a method. In this case the classname parameter is used as class name.
  • classname – Name of parent class.
  • off – If True, the starting value for the complexity is set to 1, otherwise to 0.
class radon.visitors.HalsteadVisitor(context=None)

Visitor that keeps track of operators and operands, in order to compute Halstead metrics (see radon.metrics.h_visit()).

Harvesters

class radon.cli.harvest.Harvester(paths, config)

Base class defining the interface of a Harvester object.

A Harvester has the following lifecycle:

  1. Initialization: h = Harvester(paths, config)
  2. Execution: r = h.results. results holds an iterable object. The first time results is accessed, h.run() is called. This method should not be subclassed. Instead, the gobble() method should be implemented.
  3. Reporting: the methods as_json and as_xml return a string with the corrisponding format. The method to_terminal is a generator that yields the lines to be printed in the terminal.

This class is meant to be subclasses and cannot be used directly, since the methods gobble(), as_xml() and to_terminal() are not implemented.

__init__(paths, config)

Initialize the Harvester.

paths is a list of paths to analyze. config is a Config object holding the configuration values specific to the Harvester.

as_codeclimate_issues()

Format the results as Code Climate issues.

as_json()

Format the results as JSON.

as_xml()

Format the results as XML.

gobble(fobj)

Subclasses must implement this method to define behavior.

This method is called for every file to analyze. fobj is the file object. This method should return the results from the analysis, preferably a dictionary.

results

This property holds the results of the analysis.

The first time it is accessed, an iterator is returned. Its elements are cached into a list as it is iterated over. Therefore, if results is accessed multiple times after the first one, a list will be returned.

run()

Start the analysis. For every file, this method calls the gobble() method. Results are yielded as tuple: (filename, analysis_results).

to_terminal()

Yields tuples representing lines to be printed to a terminal.

The tuples have the following format: (line, args, kwargs). The line is then formatted with line.format(*args, **kwargs).

class radon.cli.harvest.CCHarvester(paths, config)

A class that analyzes Python modules’ Cyclomatic Complexity.

class radon.cli.harvest.RawHarvester(paths, config)

A class that analyzes Python modules’ raw metrics.

class radon.cli.harvest.MIHarvester(paths, config)

A class that analyzes Python modules’ Maintainability Index.

Changelog

4.1.0 (Jan 28, 2020)

  • Support Python 3.8 (thanks to @brnsnt): #185

4.0.0 (Sep 19, 2019)

  • Support file configuration overrides, thanks @tonybaloney: #179
  • Add support for analyzing Jupyter notebooks, thanks @tonybaloney: #181

3.0.1 (Feb 03, 2019)

  • Automatically exclude binary files, instead of producing an error: #166

3.0.0 (Jan 26, 2019)

  • Include files with no extension but a Python shebang (thanks @hawkeyej): #155
  • Fix calculation of total complexity for classes: #156
  • Update Colorama dependency to avoid conflicts with pytest: #164
  • Fix raw metrics, which were completely broken

2.4.0 (Oct 11, 2018)

  • Add a __main__ module (thanks @douardda): #153
  • Add –output-file option (thanks @douardda): #154

2.3.1 (Oct 02, 2018)

  • Quickfix for Python 2.7
  • Add official Python 3.7 support

2.3.0 (Oct 02, 2018)

  • Add Halstead command and harvester (thanks @rwbogl): #136
  • Add –json, –exclude, –ignore to radon hal (thanks @rwbogl): #138
  • Add –functions to radon hal (thanks @rwbogl): #147
  • Add documentation for the radon hal subcommand (thanks @rwbogl): #150

2.2.0 (Jan 11, 2018)

  • Add an option to show closures when Radon is used from flake8: #135

2.1.1 (Sep 07, 2017)

  • Fix critical bug in Python 2 that prevented analysis of files with no comments at the start of the module: #133

2.0.3 (Aug 30, 2017)

  • Fix encoding issues for all commands: #115 and #127

2.0.2 (Jun 04, 2017)

  • Update mando dependency: #120

2.0.1 (Jun 02, 2017)

  • Fix bug in the error message of Flake8’s plugin: #121

2.0.0 (May 30, 2017)

  • Add --sort option to mi command: #100
  • Add comment stats summary when using the -s, --summary option of the raw command: #110
  • Fix encoding bug: #114
  • Fix raw metrics (ensure that LOC = SLOC + Multi + Single Comments + Blank): #118
  • Python 2.6 is not supported anymore

1.5.0 (Mar 14, 2017)

  • Use UTF-8 or RADONFILESENCODING to open files: #86
  • Fix raw analysis bug on docstrings: #106

1.4.2 (Jul 26, 2016)

  • Use flake8-polyfill in order to keep compatibility with Flake8 2.x and 3.x: #92

1.4.0 (Jun 03, 2016)

  • Add fingerprint to Code Climate issues: #88.
  • Ensure the Code Climate issues have integer location values: #89.
  • Count async def, async for and async with towards CC: #90.

1.3.0 (Mar 02, 2016)

  • Modify behaviour of --show-closures. Now inner classes are added to the output as well: #79.
  • Fix bug in is_multiline_string: #81.

1.2.2 (Jul 09, 2015)

  • Add plugin for flake8 tool: #76.

1.2.1 (May 07, 2015)

  • The XML output now contains the line numbers: #75.

1.2 (Jan 16, 2015)

  • Backwards incompatible change regarding to CC of lambda functions and nested functions: #68.
  • Fix the bug that caused classes with only one method have a CC of 2: #70.

1.1 (Sep 6, 2014)

  • Make -n, –min and -x, –max effective everywhere (in JSON and XML exporting too): #62.
  • Fix the bug that prevented JSON/XML export when one file had errors during the analysis: #63.
  • Add an explanations and various examples to the docs so that programmatical use of Radon is easier: #64.

1.0 (Aug 15, 2014)

  • Add --xml option to cc command: #49.
  • Officialy support Python 3.4.
  • Remove pathfinder: #59.
  • Reduce drastically unit-testing time: #56.
  • Update documentation (http://radon.readthedocs.org/en/latest/): #60.

0.5.3 (Aug 1, 2014)

  • Encode the source code to bytes if that’s possible (Python 3).
  • Show help if no command is given.
  • Add support to read code from stdin (thanks @io41): #55.
  • Move the tests inside the radon directory: #58.

0.5.2 (Jul 24, 2014)

  • Fix while … else bug: #53.

0.5.1 (Mar 4, 2014)

  • Fix –total-average behavior.

0.5 (Feb 17, 2014)

  • Add -i, –ignore option to ignore directories: #39.
  • Add –no-assert option to cc command to avoid assert statements: #42.
  • Add -j, –json option to raw command (thanks @cjav): #45.
  • Add –total-average option to cc command: #44.
  • Add –version global option: #47.

0.4.5 (Dec 16, 2013)

0.4.4 (Nov 20, 2013)

  • Add -j option to cc command: #33.
  • Use pathfinder and improve iter_filenames: #31.
  • Complete the documentation: #18.
  • Add -s, –summarize option to raw command (thanks @jsargiot): #36.

0.4.2 (Jun 25, 2013)

  • raw command failed on almost-empty files: #29.

0.4.1 (Jun 16, 2013)

  • Turn off colors when not printing to a tty (thanks @kennknowles): #26.
  • Fixed #27 (endline could be float(‘-inf’) sometimes).

0.4 (Apr 26, 2013)

  • Added -s option to mi command: #19.
  • Added -o option to cc command to sort output: #20.
  • Added endline attribute to Function and Class objects: #25.

0.3 (Nov 2, 2012)

  • Code coverage to 100%, runs from Python 2.6 up to 3.3 and on PyPy as well.
  • Created a documentation at https://radon.readthedocs.org: #5.
  • Made the codebase compatible with PyPy: #9.
  • Ported cli.py to Python 3: #14.
  • More tests: #15.
  • Minor fixes: #11, #12, #13, #17.

0.2 (Oct 11, 2012)

Initial version.

0.1 (Never)

There was no 0.1.

Indices and tables