With PEP8 and PEP257, Python coding that is not embarrassing to show to people!

Introduction

Hello. Immediately, is the source code you wrote easy to read?

There are many opportunities for people other than yourself to see the code you wrote, for example, when co-developing with multiple people, publishing it on the Internet, or delivering it. If the code you write at such times is well-formatted, you will be able to understand it quickly and without misunderstandings, not only for the reader but also for reviewing your own code.

In such cases, the conventions used to format Python code are ** PEP 8 ** and ** PEP 257 **.

In this article, I will introduce some typical rules that can be understood casually and achieve the minimum appearance **, instead of strictly following the contents of PEP 8 and PEP 257. To do.

Shebang, magic comment

#!/usr/bin/env python
# -*- coding: utf-8 -*-

First of all, this is often written at the beginning of the code. The first line is ** Shebang ** and the second line is called ** Magic Comment **.

** Shebang ** describes something like "Please run this file with this program".

By writing this, when you want to execute this code (temporarily named sample.py),

$ python sample.py

not

$ ./sample.py

You will be able to execute it with the command of.

Next is ** magic comment **, which according to PEP8 is ** unnecessary ** if it is Python3 source code and written in UTF-8.

The magic comment describes the character encoding of the written code, and it seems that it should not be written because the default character code is UTF-8 in Python3.

import statement

There are three main rules for import statements.

# OK
import os
import sys

# NG
import sys, os
from sklearn.model_selection import GridSearchCV, train_test_split
import os
import sys

from sklearn.model_selection import GridSearchCV, train_test_split

from mypackage import sample

Docstring

A description of the defined function or class. This is a lot of work to describe, but it looks different with and without it.

def my_func(x):
    """
Returns the squared value.

    Parameters
    ----------
    x : int
Target integer value

    Returns
    -------
    y : int
Input squared value
    """
    y = x ** 2
    return y

Enclose the Docstring in ** three double quotes **. Single quotes are NG. You can write the content after the double quoted line.

#This is also OK
def my_func_hoge(x):
    """Returns the squared value.

    Parameters
    ----------
    x : int
Target integer value

    Returns
    -------
    y : int
Input squared value
    """
    y = x ** 2
    return y


#Let's write at least a summary.
def my_func_fuga(x):
    """Returns the squared value."""
    y = x ** 2
    return y

On the first line, write a summary of the target function or class. As a caveat, make sure that the last character is a half-width period **.

Insert a blank line after the summary to enumerate the arguments, and after the argument, insert a blank line in the same way to enumerate the return values.

It seems that Jupyter etc. may be good if you write this, but the explanation here is omitted.

Indent

This is so-called indentation. Use ** 4 spaces ** instead of tabs. However, when using tensorflow, the indentation tends to be deep, so two spaces are acceptable.

#If the argument of the function becomes long, a line break is made according to the left parenthesis position.
a = long_name_function(hikisu_ichi, hikisu_ni,
                       hikisu_san, hikisu_yon)

#Lower the indent and start a new line
b = long_name_function(
    hikisu_ichi, hikisu_ni,
    hikisu_san, hikisu_yon)

#Line breaks with indentation lowered from the middle are NG
c = long_name_function(hikisu_ichi, hikisu_ni,
    hikisu_san, hikisu_yon)

Line breaks in long formulas

#It is OK if it is unified whether to start a new line before or after the calculation formula
result_1 = (sushiki_ichi
            + sushiki_ni
            - (sushiki_san - susiki_yon)
            - susiki_go)

result_2 = (sushiki_ichi +
            sushiki_ni -
            (sushiki_san - susiki_yon) -
            susiki_go)

Line spacing

In principle, leave two lines at the top level, that is, line breaks without indentation, and one or less lines otherwise.

Whether to open one space in the line

# OK
hoge = {'fuga': [0]}

# NG
hoge = { 'fuga': [ 0 ] }
# OK
if a == b:
    c = {'d': 1}

# NG
if a == b :
    c = {'d' : 1}

#The exception is the colon used for slicing
array[2:5]
a = i + 1
b = c >= d
e = f not in g_list
h = j and k

#However, it is used to describe default parameters in functions, etc.=Do not leave space on both sides of
def hoge(piyo=None):
    pass

#Used to describe arguments when specifying function keywords=Do not leave space on both sides of
piyopiyo = hoge(piyo=1)
x = (b + (b**2 - 4*a*c) ** 0.5) / (-2*a)

Summary

How was it? This time, I haven't covered all of PEP 8 and PEP 257, but I hope you can understand it roughly as to what you should pay attention to.

I would be very happy if you read this article and would like to pursue readable and good looking coding.

reference

Recommended Posts

With PEP8 and PEP257, Python coding that is not embarrassing to show to people!
Comply with Python coding standard PEP8
Fractal to make and play with Python
How to use is and == in Python
I tried to implement deep learning that is not deep with only NumPy
Read CSV file with Python and convert it to DataFrame as it is
Scraping tabelog with python and outputting to CSV
MessagePack-Try to link Java and Python with RPC
Python log is not output with docker-compose up
Prepare a development environment that is portable and easy to duplicate without polluting the environment with Python embeddable (Windows)
Building an environment to comply with the Python coding standard (PEP8) with Eclipse + PyDev
What are you comparing with Python is and ==?
[Python] Mention to multiple people with Slack API
Try to find the probability that it is a multiple of 3 and not a multiple of 5 when one is removed from a card with natural numbers 1 to 100 using Ruby and Python.
It is easy to execute SQL with Python and output the result in Excel
I want to handle optimization with python and cplex
Note that writing like this with ruby is writing like this with python
Try to operate DB with Python and visualize with d3
It's not easy to write Python, it's easy to write numpy and scipy
[Python] tkinter Code that is likely to be reused
[Python] How to write a docstring that conforms to PEP8
[Python] pandas Code that is likely to be reused
Something to enjoy with Prim Pro (X-Play) and Python
When writing to a csv file with python, a story that I made a mistake and did not meet the delivery date
A learning roadmap that allows you to develop and publish services from scratch with Python
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
[VLC] How to deal with the problem that it is not in the foreground during playback
Easy to use Nifty Cloud API with botocore and python
After all it is wrong to cat with python subprocess.
How to test that Exception is raised in python unittest
screen and split screen with python and ssh login to remote server
Generate a password that is easy to remember with apg
[Python] How to play with class variables with decorator and metaclass
How to connect to various DBs from Python (PEP 249) and SQLAlchemy
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
Send experiment results (text and images) to slack with Python
Tips for coding short and easy to read in Python
Try to bring up a subwindow with PyQt5 and Python
How to do Bulk Update with PyMySQL and notes [Python]
[Let's play with Python] Image processing to monochrome and dots
How to write a metaclass that supports both python2 and python3
Convert video to black and white with ffmpeg + python + opencv
I tried to make GUI tic-tac-toe with Python and Tkinter
I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python
The story that the private key is set to 600 with chmod
Get additional data to LDAP with python (Writer and Reader)
This and that for using Step Functions with CDK + Python
How to log in to AtCoder with Python and submit automatically
Module summary that automates and assists WebDriver installation with Python
When I tried to use pip with python, I was told that XML_SetHashSalt could not be found.
How to deal with the problem that the current directory moves when Python is executed from Atom
[Python] What is pip? Explain the command list and how to use it with actual examples
I was surprised at how to save objects with python, which is lean and very energy-saving.
NameError: global name'dot_parser' is not defined and what to do when it comes up in python
Programming with Python and Tkinter
Encryption and decryption with Python
Python round is not strictly round
Python and hardware-Using RS232C with Python-
Connect to Wikipedia with Python
Post to slack with Python 3
Python list is not a list