Giter Site home page Giter Site logo

rubik / radon Goto Github PK

View Code? Open in Web Editor NEW
1.6K 33.0 113.0 2.65 MB

Various code metrics for Python code

Home Page: http://radon.readthedocs.org/

License: MIT License

Python 99.15% Makefile 0.53% Dockerfile 0.31%
python cli static-analysis code-analysis quality-assurance

radon's Introduction

Radon

Codacy badge

Travis-CI badge

Coveralls badge

PyPI latest version badge

Radon license


Radon is a Python tool that computes various metrics from the source code. Radon can compute:

  • McCabe's complexity, i.e. cyclomatic complexity
  • raw metrics (these include SLOC, comment lines, blank lines, &c.)
  • Halstead metrics (all of them)
  • Maintainability Index (the one used in Visual Studio)

Requirements

Radon will run from Python 2.7 to Python 3.10 (except Python versions from 3.0 to 3.3) with a single code base and without the need of tools like 2to3 or six. It can also run on PyPy without any problems (currently PyPy 3.5 v7.3.1 is used in tests).

Radon depends on as few packages as possible. Currently only mando is strictly required (for the CLI interface). colorama is also listed as a dependency but if Radon cannot import it, the output simply will not be colored.

Note: Python 2.6 was supported until version 1.5.0. Starting from version 2.0, it is not supported anymore.

Installation

With Pip:

If you want to configure Radon from pyproject.toml and you run Python <3.11, you'll need the extra toml dependency:

Or download the source and run the setup file:

Usage

Radon can be used either from the command line or programmatically. Documentation is at https://radon.readthedocs.org/.

Cyclomatic Complexity Example

Quick example:

Explanation:

  • cc is the radon command to compute Cyclomatic Complexity
  • -a tells radon to calculate the average complexity at the end. Note that the average is computed among the shown blocks. If you want the total average, among all the blocks, regardless of what is being shown, you should use --total-average.
  • -nc tells radon to print only results with a complexity rank of C or worse. Other examples: -na (from A to F), or -nd (from D to F).
  • The letter in front of the line numbers represents the type of the block (F means function, M method and C class).

Actually it's even better: it's got colors!

A screen of Radon's cc command

Note about file encoding

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.

On a Continuous Integration server

If you are looking to use radon on a CI server you may be better off with xenon. Although still experimental, it will fail (that means exiting with a non-zero exit code) when various thresholds are surpassed. radon is more of a reporting tool, while xenon is a monitoring one.

If you are looking for more complete solutions, read the following sections.

Codacy

Codacy uses Radon by default to calculate metrics from the source code.

Code Climate

Radon is available as a Code Climate Engine. To understand how to add Radon's checks to your Code Climate Platform, head over to their documentation: https://docs.codeclimate.com/v1.0/docs/radon

coala Analyzer

Radon is also supported in coala. To add Radon's checks to coala, simply add the RadonBear to one of the sections in your .coafile.

CodeFactor

CodeFactor uses Radon out-of-the-box to calculate Cyclomatic Complexity.

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.

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

Quick example:

radon's People

Contributors

ajslater avatar ashanbrown avatar benabel avatar cordis-dev avatar d3x avatar dependabot[bot] avatar devdanzin avatar douardda avatar franzhaas avatar holiverh avatar io41 avatar jpignata avatar jsargiot avatar justwerns avatar kernc avatar kianmeng avatar klausondrag avatar kvgarg avatar lucasmazza avatar mgorny avatar msabramo avatar rdbliss avatar rubik avatar s-t-e-v-e-n-k avatar schettino72 avatar schlamar avatar thunderk avatar tonybaloney avatar tribals avatar wfleming avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

radon's Issues

ValueError using -s

[22:05 ~/Documents/Dprojects/Python/CoBro] radon cc -s cobro.py
Traceback (most recent call last):
  File "/usr/local/bin/radon", line 8, in <module>
    load_entry_point('radon==0.3', 'console_scripts', 'radon')()
  File "/Library/Python/2.6/site-packages/radon-0.3-py2.6.egg/radon/__init__.py", line 10, in main
    BAKER.run()
  File "build/bdist.macosx-10.6-universal/egg/baker.py", line 823, in run
  File "build/bdist.macosx-10.6-universal/egg/baker.py", line 801, in apply
  File "/Library/Python/2.6/site-packages/radon-0.3-py2.6.egg/radon/cli.py", line 171, in cc
show_complexity)
  File "/Library/Python/2.6/site-packages/radon-0.3-py2.6.egg/radon/cli.py", line 106, in _print_cc_results show_complexity)))
  File "/Library/Python/2.6/site-packages/radon-0.3-py2.6.egg/radon/cli.py", line 83, in _format_line
    compl = ' ({}) '.format(line.complexity) if show_complexity else ''
ValueError: zero length field name in format

Same result for radon cc --show_complexity cobro.py

Docstrings are a mess

After the big refactor, docstrings are very messy. Fix, bearing in mind:

  • consistency: all docstrings should be more or less the same (Sphinx style or not?)
  • accuracy: docstrings should be helpful

ERROR: invalid syntax (<unknown>, line 1404)

Cloned the repository. Did sudo python radon/setup.py install with apparent success. Installed Baker module.

[21:48 ~/Documents/Dprojects/Python/CoBro] radon cc cobro.py
cobro.py
    ERROR: invalid syntax (<unknown>, line 1404)
[21:48 ~/Documents/Dprojects/Python/CoBro] radon mi cobro.py
cobro.py
    ERROR: invalid syntax (<unknown>, line 1404)
[21:49 ~/Documents/Dprojects/Python/CoBro] radon raw  cobro.py
cobro.py
    LOC: 1404
    LLOC: 688
    SLOC: 1323
    Comments: 491
    Multi: 82
    Blank: 81
    - Comment Stats
        (C % L): 35%
        (C % S): 37%
        (C + M % L): 41%

Noting "1404" as size of input -- that line of cobro.py was: # c'est tout! a comment indented 4 ending in ! -- deleted that line and appropriate output appeared. Restoring line 1404 as #! returned the error.

External deps?

The README states that:

Radon does not depend on any other Python package (except Baker for the command line, but it is an optional dependency).

However, setup.py contains this snippet:

install_requires=['mando', 'colorama', 'pathfinder'],

Please update the README. :-)

Packaging issue with the 'tests/' directory

Hi,
as your tests directory is included in the distributed tarball as a top-level package, it is installed in python's site-packages (which can cause conflicts with other packages doing the same thing):

~ $ ls ~/lib/virtualenvs/radon/lib/python3.4/site-packages/tests
__init__.py  pathfinder_tests/  __pycache__/  run.py  test_cli.py  test_complexity_utils.py  test_complexity_visitor.py  test_halstead.py  test_other_metrics.py  test_raw.py

One option would be to exclude it from the distributed tarball, and the other option is to move it to radon.tests.

Unit tests take too much time

They're not really unit tests if they take so much time. Currently the tests inside test_cli.py run for almost 90% of the total time.

CC Bug: while ... else

I wouldn't expect the following function to have a CC of 10. It seems as if the else-statement of a while-loop adds 1 to CC and so does every line in the else-block.

def func():
    while 1:
        pass
    else:
        pass
        pass
        pass
        pass
        pass
        pass
        pass

New flag for avoid assert statements in CC

I and friend have been talking about the assert statement in the calculation of the Cyclomatic complexity (CC). We found arguments for including it, but also argument for not including it.

One argument to take into account assert statements is that an assert statement may generate a different result when executing. As Radon documentation says: “The assert statement internally roughly equals a conditional statement.”

On the other hand, it is possible to execute a Python script without running the assert statements with option –O. Although an assert increases the CC, there is no usually need to write test cases for verify the assert statements.

It seems clear that a statement introduces a new path in the code, but, it seems unclear the utility to take asserts into account. Due Radeon uses a Python parser, it counts the assert statements even –O option is indicated.

For these reason we would kindly propose a command-line flag to avoid the count of asserts as part of the CC (maybe I can sumbmit a pull request if this issue is accepted).

XML logging for cc tool doesn't respect min/max parameters

I have just recently been tested the latest release of radon to experiment with the new --xml formatting parameter added to the 'cc' tool. In so doing I discovered that the XML output seems to be ignoring either the --min and --max parameters for some reason. Even when these command line options are specified, all complexity levels are included in the resulting XML report.

While this isn't currently a deal breaker for me since I'm using another parsing tool to extract the relevant information I'm looking for from the resulting XML, I did find it non-intuitive to say the least. For example, the results produced by "radon cc -min C myproject" differ from the results produced by "radon cc -min C myproject --xml".

I assume it would be a relatively simple matter to update the tool so the XML output respects these other customization parameters as well, so this may be something to consider changing in a future release.

raw command fails if file has nothing but an empty string with line end

Hi. On version

radon==0.4.1

I got

./apps/utils/models.py
    LOC: 1
    LLOC: 0
    SLOC: 0
    Comments: 0
    Multi: 0
    Blank: 1
    - Comment Stats
        (C % L): 0%
    load_entry_point('radon==0.4.1', 'console_scripts', 'radon')()
  File "/home/apollov/.local/lib/python2.7/site-packages/radon/__init__.py", line 8, in main
    BAKER.run()
  File "/home/apollov/.local/lib/python2.7/site-packages/baker.py", line 823, in run
    value = self.apply(*self.parse(argv), instance=instance)
  File "/home/apollov/.local/lib/python2.7/site-packages/baker.py", line 801, in apply
    return cmd.fn(*newargs, **newkwargs)
  File "/home/apollov/.local/lib/python2.7/site-packages/radon/cli.py", line 227, in raw
    log('{0}(C % S): {1:.0%}', indent, comments / float(mod.sloc))
ZeroDivisionError: float division by zero

Where ./apps/utils/models.py contains just 1 empty string with line end:

\n

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.