/    /  Python – Coding Style

Python – Coding Style

In this tutorial you will learn python in detail.

 

PEP the Python Enhancement Proposal is a document that provides guidelines and best practices on how to write python code. It describes new features for python like design and style for the community. This document was written by Guido van Rossum, Barry Warsaw and Nick Coghlan. 

 

PEP 8 improves the readability of python code. You’ll have a question on why writing readable code? As Guido van Rossun, ‘You’ll spend hours of time or sometimes a whole day to write a piece of code. Once you’ve written it, you will never go back to write it again. But there comes a time you’ll definitely have to read it again. Now you may not remember why the code is written and what it does, so readability matters.

 

And if you are new to python coding it is difficult to remember what a piece of code does after a few days. For beginners, following the rules of PEP 8 makes learning Python a much more pleasant task. 

Writing clear and readable code shows developers professionalism.

 

Let’s see what are those guidelines in detail. 

 

Naming Conventions 

 

While writing python code, there will be a lot of things that you come across like, variables, functions, classes, packages, and so on. Choosing sensible names will make you to figure out, from the name, what a certain variable, function, or class represents. This helps in avoiding errors that are difficult to debug. 

 

Naming Styles 

 

Below shows some of the common styles in python code. 

  • Function – Use a lowercase word. Separate words by underscores to improve readability. 
  • Variable – Use a lowercase single letter, word, or words. Separate words with underscores to improve readability. 
  • Class – Each word should start with a capital letter. Do not separate words with underscores. This style is called camel case. 
  • Method – Use a lowercase word or words. Separate words with underscores to improve readability. 
  • Constant – Use an uppercase single letter, word, or words. Separate words with underscores to improve readability.
  • Module – Use a short, lowercase word or words. Separate words with underscores to improve readability.
  • Package – Use a short, lowercase word or words. Do not separate words with underscores.

 

How to Choose Names 

 

A better way of choosing names would be like this: 

 

>>> # Recommended 
>>> name = 'Python PEP'
>>> first_name, last_name = name.split() 
>>> print(last_name, first_name, sep=', ') 
'Python, PEP'   

 

The above example shows a clearer understanding of what variables represents. Also do not use abbreviations when choosing names. This would make difficulty in guessing how you abbreviated it. Every time try to use the most concise but descriptive names. 

 

Code Layout 

 

In this session you will learn about vertical whitespaces, line length to improve the readability of your code.  

 

Blank lines 

 

To improve readability of code vertical whitespace or blank lines are very important. It is hard to read and understand if the code is bunched up together. Here are few guidelines on how to write code with vertical whitespace.

 

Top-level functions and classes should be with two blank lines:

 

Top-level functions and classes handle separate functionality, so they will be clear if you put them in code with extra vertical space.

 

Example:

 

class MyFirstClass:
   pass


class MySecondClass:
    pass


def top_level_function():
    return None

 

Method definitions inside classes should be with a single blank line:

 

Example:

 

class MyClass:
   def first_method(self):
        return None

   def second_method(self):
        return None

 

Using blank line inside functions:

 

Sometimes you need to write several lines of code before the return statement within a function. It makes reader to understand what is returned.

It is a good practice to split the code into sections, hence it helps reader understand how these sections are related to one another.

 

Maximum Line Length and Line Breaking

 

To avoid line wrapping and to open multiple files next to one another, PEP 8 suggests lines should be limited to 79 characters.

Python considers line continuation if the code is enclosed within parentheses, brackets or braces.

 

Example:

 

def function(arg_one, arg_two,
arg_three, arg_four):
    return arg_one

 

you can also use backslashes to break lines.

 

Example:

 

from mypkg import example1, \
    example2, example3

 

if you want to break lines around binary operators like +, *, it should occur before the operator.

 

Example:

 

total = (first_variable
        + second_variable
         - third_variable)

 

Indentation

 

Indentation is extremely important in Python. Indentation in Python determines how statements are grouped together.

PEP 8 laid out key indentation rules.

  • Use 4 consecutive spaces to indicate indentation.
  • Prefer spaces over tabs.

 

Tabs vs. Spaces

 

You can either use spaces or tabs when indenting code. In Python 2 you can have a mixture of tabs and spaces to indent your code, it won’t raise errors when running the code. To check the consistency, you can add -t flag when running Python 2 code from the command line. The interpreter will issue warning if you are inconsistent with tabs and spaces.

 

$ python2 -t code.py
code.py: inconsistent use of tabs and spaces in indentation

 

using –tt will tell you were the inconsistencies are.

 

$ python2 -tt code.py
File "code.py", line 3
   print(i, j)
             ^
TabError: inconsistent use of tabs and spaces in indentation

 

But in Python 3 you cannot mix tabs and spaces. You must be consistent with tabs or spaces in Python 3. You must always use 4 consecutive spaces to indicate indent.

 

PEP 8 provides two alternatives to improve readability:

  • Add a comment after the final condition.

 

x = 6
if (x > 4 and
   x < 10):
   # Both conditions satisfied
    print(x)

 

  • Add extra indentation on the line continuation.

 

x = 5
if (x > 3 and
       x < 10):
    print(x)

 

Alternatively, you can use hanging indent.

 

Example:

 

var = function(
  arg_one, arg_two,
arg_three, arg_four)

 

To distinguish continued line in the code present in the function, it is better to use double indent.

 

# Not Recommended
def function(
   arg_one, arg_two,
   arg_three, arg_four):
    return arg_one

 

 

#recommended
def function(
       arg_one, arg_two,
       arg_three, arg_four):
    return arg_one

 

Where to place closing brace

  • Line up the closing brace with the first non-whitespace character of the previous line:

 

list_of_numbers = [
   1, 2, 3,
   4, 5, 6,
   7, 8, 9
    ]

 

  • Line up the closing brace with the first character of the line that starts the construct:

 

list_of_numbers = [
   1, 2, 3,
   4, 5, 6,
   7, 8, 9
]

 

 

Comments

 

To remember the line of code and to make someone understand why the code is written, it is important to comment. You can use block comments or inline comments for this purpose.

 

Documentation Strings

 

These are enclosed in double(“””) or single(‘’’) quotation marks. For one-line docstrings, keep the “”” on the same line.

 

Whitespace in Expressions and Statements

 

It is very helpful to use whitespace in expressions and statements. Otherwise it will be difficult to understand bunched together code.

Use whitespace around binary operators like assignment operators, comparison and Boolean operators. When there is more than one operator, do not add space before and after each operator. Instead add whitespace around the operator with the lowest priority.

 

# Recommended
y = x**3 + 7
z = (x+y) * (x-y)

# Not Recommended
y = x ** 3 + 7
z = (x + y) * (x - y)


# Not recommended
if x > 5 and x % 2 == 0:
   print('x is larger than 5 and divisible by 2!') 


# Recommended
if x>5 and x%2==0:
    print('x is larger than 5 and divisible by 2!')

 

Maintain same amount of space on either side of the operator.

  • When to Avoid Adding Whitespace
  • Below is a list describing where to avoid adding whitespaces.
  • Immediately inside parentheses, brackets, or braces:
  • Before a comma, semicolon, or colon:
  • Before the open parenthesis that starts the argument list of a function call:
  • Before the open bracket that starts an index or slice:
  • Between a trailing comma and a closing parenthesis:
  • To align assignment operators:

Never ignore PEP 8 rules for coding style.