Summary about pythonic style (1): PEP8

background

I've changed jobs and am about to use python in earnest at work, so I'd like to summarize the pythonic coding style I examined earlier as a review.

UPDATE: Part 2 has been updated.

Contents of this page

Adhering to PEP 8 is the first basic. There are already a lot of existing articles, including the existing Japanese translation, so I would like you to give priority to that. Original Japanese translation

Other Qiita articles: Compliant with Python coding standard PEP8 Summary of Python coding standard PEP8 (1)

Purpose of creation

(Somehow, I feel that this kind of thing is proclaimed by someone digging out on a regular basis.)

The second time I will summarize the contents that are not in PEP 8. If you have any supplements or suggestions (I'm not Japanese, so please point out in Japanese), please give me Masakari. Then to the main subject ~

Premise

Code layout

Indent

test = long_function(var1, var2,
                     var3, var4)
def long_function(
        var1, var2,var3,
        var4):
    print(val_one)
test = long_function(
    var1, var2, var3,
    va4)
if (hoge1_is_true and
    hoge2_is_true):
    #comment
    do_something()

#OR
if (hoge1_is_true
        and hoge2_is_true):
    do something
my_list = [
    1, 2, 3,
    4, 5, 6
    ]

#OR
my_list = [
    1, 2, 3,
    4, 5, 6
]

Line length

Use parentheses:

if (hoge1 and hoge2
        hoge3 and hoge4):
    do_something

""use:

with open(filepath1, "r") as file1, \
     open(filepath2, "r") as file2:
    do_something

Line break location

Line breaks before operators for readability

revenue = gacha1_price * payers1
          + gacha2_price * payers2
          + gacha3_price * payers3

Blank line

Source file Encoding

import

import pandas
import numpy
from sklearn.linear_model import LinearRegression, LogisticRegression

Module level dunder statement location

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

other

#Yes
if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

#No:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

Quotation

"""This is how you write 
documentatoin string.
"""

Space in code

Avoid the following spaces

#Yes
buger(bread[2], {cheese: 1})
#No
buger( bread[ 2 ], { cheese: 1 } )
#Yes
a_tuple = (0,)
#No
a_tuple = (0, )
#Yes
if a: print x, y; x, y = y, x
#No
if a : print x , y ; x , y = y , x
#Yes
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
#No
ham[1: 9], ham[1 :9], ham[1:9 :3]
#Yes
ham[lower+offset : upper+offset], ham[: upper_fn(x) : step_fn(x)]
#No
ham[lower + offset:upper + offset]
#Yes
func_call(params)
#No
func_call (params)
#Yes
dct['key'] = lst[index]
#No
dct ['key'] = lst [index]
#Yes
x = 1
y = 2
long_variable = 3

#No
x             = 1
y             = 2
long_variable = 3
#Yes
def complex(real, imag=0.0):
    return magic(r=real, i=imag)
#No
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)

Let's put the following space

#Yes
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

#No
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
#Yes
def munge(input: AnyStr): ...
def munge() -> AnyStr: ...

#No
def munge(input:AnyStr): ...
def munge()->PosInt: ...
#Yes
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...

#No
def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000): ...

Trailing comma

#Yes
FILES = ('setup.cfg',)
#No
FILES = 'setup.cfg',
#Yes
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )

#No
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

comment

General

Block comment

Inline comment

Documentation description

About naming

Basic

b  #Single lowercase
B  #Single uppercase
lowercase  #All lowercase
lower_case_with_underscores  # _Lowercase letters with
UPPERCASE  #All capital letters
UPPER_CASE_WITH_UNDERSCORES  # _Uppercase with
CapitalizedWords  #Uppercase initials
CapitalizeAbbreviationLikeHTTP  #For capital initials, all proper abbreviations should be capitalized
mixedCase  #composite
Capitalized_Words_With_Underscores  #Ugly capital initials+ _

_single_leading_underscore  #When using only inside, like private
single_trailing_underscore_ #To avoid conflicts with Python keywords
__double_leading_underscore  #Qualifications when naming class variables
__double_leading_and_trailing_underscore__  #Never define it yourself

Use of naming style

Other naming rules

Recommended Posts

Summary about pythonic style (1): PEP8
Summary about pythonic style (2): Other scraping
Summary about Python scraping
Summary about Python3 + OpenCV3
Summary and common errors about cron
EP 2 Follow the PEP 8 Style Guide