良好的python code创作之道

python coding standards from PEP8

写在前面

  A Foolish Consistency is the Hobgoblin of Little Minds!
  尽信书,则不如无书!这是从pep8规范上摘抄下来的话,正如代码规范是为了提升代码阅读和编码质量一样,任何规范的首要原则就是一致性。我们应该遵循已经存在了的项目代码风格,而不要为了规范而特意打破原来的平衡,当然如果你重头开始一个新的项目,那么最好使用这些约定来帮助你和他人更好的理解和阅读代码。

一行代码学习完所有规范

>>>pip install flake8  # or
>>>pip install pylint

  最好的学习方式就是安装上述代码规范检查工具,当然并不限于以上两种,这类的规范工具很多,选择一种适合自己的且只安装一种,因为它们之间也会为了某些标准而打架。当然如果你并不满意或者不需要某种规范,可以按照下载工具的官方文档去设置忽略它们,毕竟自己码代码码的开心才最重要!

还是要学习如何写

  尽管我们可以安装工具来规范自己,时刻提醒自己,但不学习如何规范的编写,到时候满屏的波浪线会让你崩溃。下面是我自己总结的一些基础的编码风格和规范,我会按照编写一个py文件的顺序来介绍。

一个固定的开头

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""My favorite way.

first line: use absolute path of python.
second line: appoint the encode of file.
"""
#!/usr/bin/env python
"""Another way.

use env path better than the way above.
"""

#!/usr/bin/python2
"""python2!"""
#!/usr/bin/python3
"""python3!"""
# coding: utf-8
# coding=utf-8
"""A short way.

but I don't think it beautiful than my way just in format.
"""

  正如你所看到那样,仅仅开头就花样百出。但我仍然没有列出所有的方式,你也不必纠结有多少种写法,选择一种你最喜欢的方式足以。
  那么为啥要写这两行呢?

  • #!/usr/bin/python
      指定所用的python解释器,python后面的数字指定python版本;当然这行代码在windows下意义不大,主要是针对linux/unix用户,如果在linux/unix下加上这行代码,并且当前用户对py文件拥有可执行权限的话,可以在终端直接输入./filename.py执行py文件(验证时请注意使用ls -all查看权限,有时root也不一定拥有可执行权限,使用chmod进行修改即可验证)。不加这行代码或者当前用户没有权限,则使用python filename.py执行。
  • -*- coding: utf-8 -*-
      指定文件编码,这个主要是针对python2的py文件中如果出现非ASCII字符会报错,即使是在注释中;而python3默认utf-8编码,可以不加此行代码,但为了代码的可移植性,请务必添加。

规范使用import

import sys  # first import the standard library
            # put a blank line
import requests  # then import the third party
                 # put a blank line
import my_module  # finally use own module
import os, sys  # don't use this, separate them in different line

# import like this
import os
import sys  

# this is ok
from subprocess import Popen, PIPE

# try not use this as possible as you can
from os import *

开始正式码代码

  • 代码编排
1   import os
2              
3
4   # put two blank lines
5   class CodeStyle:
6      
7       def use_four_space_for_indent(self):
8       """Four space for indent."""
9           pass
10
11      def put_one_blank_line(self):
12      """One blank line between the class method."""
13          pass
14
15
16  def alone_function():
17  """Get two blank lines between the class."""
18      pass
19
20
21  if __name__ == '__main__':
22  """Also two lines."""
23      print('the last line!')  # put a blank line in the last, like code line mark number 24
24
  • 命名规范
# use some meaningful words

import my_module  # lowercase, use underscore


THE_CONSTANT_NAME = 1  # uppercase, use underscore


class MyClass:  # CapWords
    
    def __init__(self):
        self.the_class_attr = 1  # lowercase, use underscore

    def class_method_name(self): # lowercase, use underscore
        pass


def the_function_name(param_name):  # lowercase, use underscore
    the_variable_name = 1  # lowercase, use underscore
    
  • 有趣的空格
# use like this
x = 1
y = 1
long_variable = 3

# don't
x             = 1
y             = 1
long_variable = 3

# no space between '=', but still has one space in parameters
def function1(param1, param2, param3=3):
    return function2(param1=1, param2=2)

# some more examples
# 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
if foo == 'hehe':
    return True

for i in list:
    x += i

while True:
    do_this()

# No
if foo == 'hehe': return True
for i in list: x += i
while True: do_this() 

# comment
# there has one space after '#'
  • 文档和注释
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Module document.

use """ """, write something important.
first line first word in document uppercase.
the module document before import statement, 
like this.
"""
import my_module


class MyClass:
    """MyClass document, single line."""

    # or

    """MyClass document.

    multi-line.
    and many words.
    and...
    """

    def __init__(self):
        """Init the object."""
        pass


def function(param1, param2):
    """
    This is a groups style docs from google.

    Parameters:
        param1 - this is the first param
        param2 - this is a second param

    Returns: 
        This is a description of what is returned

    Raises: 
        KeyError - raises an exception
    """
    pass


# and this is a single comment, notice the space after '#'

# we should use English comment as possible as we can.
# it can improve our language sense, so you can see it
# why I try to write so many poor English comments and
# I'm just kidding.  that's advice from pep8, but we 
# should follow our project language that the most people 
# can accept it.  notice use two space after a 
# sentence-ending period in multi-sentence comments, 
# except the last one.
# 
# the best way to write comment is don't use two language
# in comments! 

编码结束

  have fun in python!

你可能感兴趣的:(良好的python code创作之道)