Codementor Events

Simple tricks; better Python

Published Jun 10, 2018Last updated Jun 13, 2018
Simple tricks; better Python

At school, teachers always emphasized to me that spelling is important. And grammar. But it was too easy to get away with not worrying about those things when all I had was a pencil, paper, and later, a typewriter.

But then along came word processors. And not only could I now read what I was writing, and fix it if it was wrong without starting again, but also my spelling and grammar improved dramatically. Because every time I made an error the word processor was in my face, complaining and telling me I needed to do better.

Spell check taught me too spell!

It’s easy to develop in ways that mimick using a typewriter, even if you don’t know what a typewriter is (many people these days apparently don’t!)

Here are two Python tools that, like the spellchecker, can help you improve with very little effort, but this time, it’s your Python code that gets better.

First autopep8. Get it with
pip install autopep8

PEP8 is the adopted standard for code style in Python. It helps to ensure code consistency, readability and general code quality.

I run autopep8 like this:
autopep8 -d -v demo_class.py

Here is what autopep8 tells me about my code:
`
[file: demo_class.py]
---> Applying global fix for E265
---> 7 issue(s) to fix {'E302': {21, 11, 5}, 'E301': {8, 17, 24}, 'E305': {27}}
---> 0 issue(s) to fix {}
--- original/demo_class.py
+++ fixed/demo_class.py
@@ -2,11 +2,14 @@
script illustrating class hierarchy, inheritance and super()
"""
+
class Person():
def speak(self):
print("Hello from Person")
+
def talk(self):
print("I'm a Person talking not speaking")
+

class Female(Person):
def speak(self):
@@ -14,15 +17,19 @@
print("Can a Person class speak in Female class?")
super().speak()
print("Yes!")
+
def talk(self):
print("Let Female's superclass do the talking...")
super().talk()
+
class Male(Person):
def speak(self):
print("Hello from Male")
+
def talk(self):
print("Blah blah blah")
+

p = Person()
f = Female()
`

Let's explain what's going on.

This line:
---> 7 issue(s) to fix {'E302': {21, 11, 5}, 'E301': {8, 17, 24}, 'E305': {27}}
shows the issue count, and associated issue numbers, with the line numbers on which the issue occurs.

You can find out what the issue numbers mean by typing:

autopep8 --list-fixes

which outputs the following (partial output only shown).
E101 - Reindent all lines.
E112 - Fix under-indented comments.
E113 - Fix over-indented comments.
E115 - Fix under-indented comments.
E116 - Fix over-indented comments.
E121 - Fix a badly indented line.

Where you see + autopep8 is telling you that a fix was made (- indicates the "before").
@@ -14,15 +17,19 @@ shows fixed lines vs. former lines (was 15 and 15, now 17 and 19).
Now, if I run autopep8 this way it fixes the program for me automatically:
autopep8 -i demo_class.py

But that might be living dangerously (perhaps it’s going to want to do
something I don’t want it to do). Always do this
autopep8 -d -v -v demo_class.py

before this
autopep8 -i demo_class.py

to stay safe is my advice!

Pylint

Now, let's look at a tool called a linter; pylint specificically. Get it with
pip install pylint.
pylint analyzes Python code looking for errors, suspicious constructs and style issues. When I type pylint myprog.py look at what Pylint makes of this code:

learnnosql.py

Using config file .pylintrc
************* Module src.learnnosql
C: 30, 0: Empty function docstring (empty-docstring)
E: 43, 4: Undefined variable 'simple_script' (undefined-variable)
W: 49,-1: String statement has no effect (pointless-string-statement)

Your code has been rated at 5.88/10 (previous run: 5.88/10, +0.00)

Interpreting

pytlint finds issues with varying levels of severity (the E/C/W etc in column 1) and describes the problem for me. And it gives me a score, letting me know if things are getting better or worse since the last run.

This linter (there are many) is driven by a .pylintrc file, which can be complex to setup. Fortunately, many such files are available to download and get started. Get one from here (or anywhere you chose):

.pylintrc file

Download the file to (say) your HOME directory. Then, when you use pylint, use the following command line:
pylint --rcfile=<path to file> etc

I would suggest, no recommend (and almost insist!) that you ALWAYS run your code through autopep8 and pylint. And your code will improve!

In a future article I will show you how to automate the execution of autopep8 and pylint. And we'll look at other useful tools too.

Let me know if you try it, and what the outcome looks like…

Discover and read more posts from Andy Miles
get started
post commentsBe the first to share your opinion
Show more replies