Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday 7 October 2020

Python Static Code Analysis

Python static code analysis with Prospector and Bandit

Not going to talk about the "why should one use code analysis tools", if you read it up to the end you'll get it!

Which code analysis tools?

Let's talk about Code Analysis in Python, what to use, why to use, experience on using it.

Currently I use only 2, and for me it's the limit of code analysis tools to use at the same time without much overhead.  Prospector & Bandit. Why two?

Well one, Bandit,  focus specifically on security on your Python code, the other has a wider range focusing on potential errors, complexity and convention violations . Both overlap in some way, with Prospector replacing Pylint, pep8 and McCabe complexity, endoing: you'll get more than enough code analysis, sometime more than you can handle. (I'll get to that latter on)

 

How to Install Bandit and Prospector?

Installation is very strait forward on both of them.

Installing Bandit is as simple as:

pip install bandit
or 
pip3 install bandit 

Installing Prospector isn't much harder:

pip install prospector[with_everything]
or 
pip3 install prospector[with_everything]

 

Running of Bandit and Prospector?

First you need your python file. In this case I've used an example one just for the sake of example, let's call it tst.py


It's a very simple program with one function, user input and screen output. Let's run first Bandit, how? Simple:

    bandit tst.py

Here's the result:

Looks like we've got a potential issue with the "input" , since we're using python3 won't be a problem but lets assume that it is. Go to the link and read the explanation, so if we're on Python2 let's swap input() with raw_input() else it's all alright.

Now running prospector, the -s flag points the profiles used, from veryhigh to verylow, in here you can opt to choose, if you don't use the flag medium shall be used, for sake of example let's go for the veryhigh :

    prospector -s veryhigh tst.py

 

 

As you can see LOTS of warnings are issued in the veryhigh (30 vs 6 on the medium profile) so use the veryhigh and high with come caution because most of the warnings in veryhigh are related to syntax and indentation aspects (pep8).

So if you apply most of the changes/fix all the warnings how will the code look like? ( DO keep in mind that sometimes you can't actually apply all the changes due to legacy code/ code dependencies, and sometimes your editor my leave some spaces/tabs between the lines which will conflict with the "veryhigh" settings)

Now your code is a bit safer and cleaner. This was a simple and silly example, try to run it on your own scripts/programs and see the differences, again in prospector don't rush into the "veryhigh" profile.