良好的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!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,999评论 4 368
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,102评论 1 302
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,709评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,439评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,846评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,881评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,062评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,783评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,517评论 1 248
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,762评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,241评论 1 264
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,568评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,236评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,145评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,941评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,965评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,802评论 2 275

推荐阅读更多精彩内容