Python编码规范

Posted Data+Science+Insight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python编码规范相关的知识,希望对你有一定的参考价值。

Python编码规范

 

空格的使用

 

使用空格来表示缩进而不要用制表符(Tab)。

和语法相关的每一层缩进都用4个空格来表示。

每行的字符数不要超过79个字符,如果表达式因太长而占据了多行,除了首行之外的其余各行都应该在正常的缩进宽度上再加上4个空格。

函数和类的定义,代码前后都要用两个空行进行分隔。

在同一个类中,各个方法之间应该用一个空行进行分隔。

二元运算符的左右两侧应该保留一个空格,而且只要一个空格就好

 

标识符命名

变量、函数和属性应该使用小写字母来拼写,如果有多个单词就使用下划线进行连接。

类中受保护的实例属性,应该以一个下划线开头。

类中私有的实例属性,应该以两个下划线开头。

类和异常的命名,应该每个单词首字母大写。

模块级别的常量,应该采用全大写字母,如果有多个单词就用下划线进行连接。

类的实例方法,应该把第一个参数命名为self以表示对象自身。

类的类方法,应该把第一个参数命名为cls以表示该类自身。

 

表达式和语句

 

采用内联形式的否定词,而不要把否定词放在整个表达式的前面。例如:if a is not b就比if not a is b更容易让人理解。

不要用检查长度的方式来判断字符串、列表等是否为None或者没有元素,应该用if not x这样的写法来检查它。

就算if分支、for循环、except异常捕获等中只有一行代码,也不要将代码和ifforexcept等写在一起,分开写才会让代码更清晰。

import语句总是放在文件开头的地方。

引入模块的时候,from math import sqrtimport math更好。

如果有多个import语句,应该将其分为三部分,从上到下分别是Python标准模块第三方模块自定义模块,每个部分内部应该按照模块名称的字母表顺序来排列。


PEP or Python Enhancement Proposal is a draft or document that has the description of Python code writing guidelines, which is the best practice to improve the Python codes’ consistency and readability. This document contains features such as Python’s Style and design which is used while writing the codes. As we know, Python has a strict format or the order to write the scripts, so that it makes it others easy to read the code; therefore nice coding style helps tremendously to the developers or others who are reading the code. The developers must follow these guidelines. In Python, we see indentation is very important for code to execute syntactically.

Functions of PEP8 in Python

In general, Pep8 is a tool where you can check your Python code conventions with the conventions in the documentation of Pep8. Let us see a few features of Pep8 documentation:

1. Indentation

This is one of the most important features for writing the codes and for reading the codes in Python. It is also known as the 4 space rule, and this rule is not as mandatory as it can be overruled for the continuation of the line. Indentation also helps to know which code belongs to which function as we use braces in other programming languages in Python; this done by following the rules of indentation.

In Pep8, the rules are use spaces in place of tabs, as the name of the rule use 4 consecutive spaces for indentation. If both these rules are used at once then this causes an error that issues a warning by the interpreter.

Example

Code:

n = 10
if n> 5:
print “n is greater”

Output:

Python PEP8-1.1

The print statement follows indentation in the above program because the “if” statement is true, then only the print statement is executed. If there is no proper indentation maintained, then it will pop an error. The output of the above code without indentation will be:

 Popular Course in this category

Python Training Program (36 Courses, 13+ Projects)36 Online Courses | 13 Hands-on Projects | 189+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.8 (9,550 ratings)

Course Price
¥1649 ¥3999
View Course


Related Courses

Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)Angular JS Training Program (9 Courses, 7 Projects)

Code:

n = 10
if n> 5:
print "n is greater"

Output:

Python PEP8-1.2

2. Naming Conventions

There are few naming rules in Pep8 for Python coding to make the codes more readable and less complex. There are many things in the code to be given a name, such as it may variables, class, methods, packages, etc. It has always been a best practice for selecting names to variables or functions or classes or packages that make sense, or they relate to what exactly the code does because using some random names for declaring would lead to ambiguity or it is highly difficult when debugging the code. Let us see a few naming styles to be used while writing codes.

For variables, you can have either one letter or word or any number of words separated by an underscore, but all these letters should be in lowercase. We can use all the letters in lowercase for naming functions or methods, which can be one word or any number of words separated by an underscore. For constants also follow the same as variables, but all the letters should be in uppercase. For class, the naming rule is that you can use one word or multiple words, but there is no separation between these multiple words, and it follows a camel case like ClassName. For packages also follow the same as naming rules of class, but instead of camel case, the package name’s letters should all be in lowercase. These all can be demonstrated in the below code.

Example

Code:

class ClassName: #Class naming rule
C = 1 #Constat naming rule
the_variable = 2020; # variable naming rule
print("The constant value is:", C)
def the_method(self): # method naming rule
print("I'm inside class ")
def insideclass(self):
print("The Variable: ",ClassName.the_variable)
self.the_method()
n = ClassName()
n.insideclass()

Output:

Python PEP8-1.3

3. Document String

This is also known as docstrings which have the document strings enclosed within both single and double quotes, which are used to define the program or any particular function or methods. The rules for applying document strings to code are:

Firstly the quotation used for documenting a block of code is done in triple quotes such as.

“This is a docstring””” and secondly where it can be used in writing docstring for all functions, public modules, classes, and methods. Note that docstrings are not necessary for non-public methods; instead, you can have comments to describe the description of what the method does. Also, note that the end triple quotes come in the same line for one line docstrings, but for multiple lines, the end triple quotes come where the docstrings end.

Example

Code:

def addition:
a, b = 0
“““ This method is for addition”””
c = a + b
“““ This method is for addition and it is addition of two numbers.
This has a formula as shown above c = a+ b
And the addition of two numbers gives the result which is stored in c”””
return c

Some of the other few Pep8 documentation rules for Python codes are:

  • We have to use UTF-8 or ASCII encoding for Python coding, and it is also a default encoding that is meant for international environments.
  • There is also a rule of where to use spaces. Spaces should be used only around the operators and after the comma, not inside the brackets or before the comma.
  • Characters should not be used for identifiers as they may lead to confusion, such as for letter “l”, which can be taken as lowercase “l” (el) and uppercase “I” and for the letter “O” capital O (oh) and number zero “0”.

There are many different document features of Pep8 for Python code styling and designing.

Conclusion

Pep8 is one of the tools for accurately writing Python codes with proper rules and styling for the codes. This documentation of rules is very important for the developers to write code that is more readable and less complex for others. To note one point, usually writing proper codes with proper comments and documents helps as codes are written only once, but many people read them many times, so the developers need to write the code to be readable and easy to understand code for others. Therefore Pep8 would help you do this.

 

参考:python面试宝典

参考:PEP8中文翻译(转)

参考:PEP 8 — the Style Guide for Python Code

参考:Python PEP8 | Functions and Examples of Python PEP8

以上是关于Python编码规范的主要内容,如果未能解决你的问题,请参考以下文章

Python编码规范整理

Python编码规范整理

Python编码规范

《Python从小白到大牛》第5章 Python编码规范

python的pep8编码规范和代码调试(pdb,ipdb,debug)

Python编码规范