Code Style

Code Style

Code Style

Python的可读性是Python的核心。可以参考pep20的原则来设计代码和pep8来规范代码格式。此外,对于很多任务,Python有一些最佳的写法(Pythonic),可以使代码简洁清晰。

pep 20

pep20 被称为Python之禅,可看作Python设计的指导原则。打开解释器,输入import this 就可以看到。

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Python之禅 by Tim Peters

优美胜于丑陋(Python以编写优美的代码为目标)
明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)
简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)
复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)
扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)
间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)
可读性很重要(优美的代码是可读的)
即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)
不要包容所有错误,除非您确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)
当存在多种可能,不要尝试去猜测
而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)
虽然这并不容易,因为您不是 Python 之父(这里的 Dutch 是指 Guido )
做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)
如果您无法向人描述您的方案,那肯定不是一个好方案;反之亦然(方案测评标准)
命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

看完后你可能觉得比较抽象,这里有一份pep 20 的示例 https://github.com/hblanks/zen-of-python-by-example
下面是其中的几个示例:

优美胜于丑陋

halve_evens_only = lambda nums: map(lambda i: i/2filter(lambda i: not i%2, nums))
#-----------------------------------------------------------------------
def halve_evens_only(nums):
    return [i/2 for i in nums if not i % 2]

明确胜于隐晦

def load():
    from menagerie.cat.models import *
    from menagerie.dog.models import *
    from menagerie.mouse.models import *
#-----------------------------------------------------------------------
def load():
    from menagerie.models import cat as cat_models
    from menagerie.models import dog as dog_models
    from menagerie.models import mouse as mouse_models

简单胜于复杂

"""
Can you write out these measurements to disk?
"""


measurements = [
    {'weight'392.3'color''purple''temperature'33.4},
    {'weight'34.0'color''green''temperature': -3.1},
    ]

#-----------------------------------------------------------------------

def store(measurements):
    import sqlalchemy
    import sqlalchemy.types as sqltypes
    
    db = sqlalchemy.create_engine('sqlite:///measurements.db')
    db.echo = False
    metadata = sqlalchemy.MetaData(db)
    table = sqlalchemy.Table('measurements', metadata,
        sqlalchemy.Column('id', sqltypes.Integer, primary_key=True),
        sqlalchemy.Column('weight', sqltypes.Float),
        sqlalchemy.Column('temperature', sqltypes.Float),
        sqlalchemy.Column('color', sqltypes.String(32)),
        )
    table.create(checkfirst=True)
    
    for measurement in measurements:
        i = table.insert()
        i.execute(**measurement)

#-----------------------------------------------------------------------

def store(measurements):
    import json
    with open('measurements.json''w'as f:
        f.write(json.dumps(measurements))

扁平胜于嵌套

"""Identify this animal. """

#-----------------------------------------------------------------------

def identify(animal):
    if animal.is_vertebrate():
        noise = animal.poke()
        if noise == 'moo':
            return 'cow'
        elif noise == 'woof':
            return 'dog'
    else:
        if animal.is_multicellular():
            return 'Bug!'
        else:
            if animal.is_fungus():
                return 'Yeast'
            else:
                return 'Amoeba'

#-----------------------------------------------------------------------

def identify(animal):
    if animal.is_vertebrate():
        return identify_vertebrate(animal)
    else:
        return identify_invertebrate(animal)

def identify_vertebrate(animal):
    noise = animal.poke()
    if noise == 'moo':
        return 'cow'
    elif noise == 'woof':
        return 'dog'

def identify_invertebrate(animal):
    if animal.is_multicellular():
        return 'Bug!'
    else:
        if animal.is_fungus():
            return 'Yeast'
        else:
            return 'Amoeba'

pep 8

pep 8 是事实上的Python代码规范。

pep 8 规定了代码格式,比如 使用4空格缩进、每行最多79字符、类定义前空两行等… 完整的pep8标准可以在https://www.python.org/dev/peps/pep-0008或http://pep8.org/查看。

有一些工具可以帮助检查格式或格式化代码。

pycodestyle可以检查代码是否符合pep8格式:
安装: pip install pycodestyle 
使用: pycodestyle main.py (如果你使用PyCharm,默认是带有格式检查的。)

autopep8可以自动将代码格式化为pep 8 风格:
安装: pip install autopep8 
用以下指令格式化一个文件: autopep8 --in-place main.py

pythonic

Pythonic可以理解为简洁直观、优雅,利用Python特性进行编码。下面是Pythonic方式的几个例子:

解包(unpacking)

#迭代列表
for index, item in enumerate(some_list):

    # 使用index和item做一些工作

交换变量 a, b = b, a

列表

  • • 创建长度为n的列表 four_nones = [None] * 4

  • • 二维列表 four_lists = [[] for __ in range(4)]

  • • 从列表创建字符串

letters = ['s''p''a''m']
word = ''.join(letters)

使用集合查找

s = set(['s''p''a''m'])
l = ['s''p''a''m']

def lookup_set(s):
    return 's' in s

def lookup_list(l):
    return 's' in l

使用集合查找会比使用列表查找快很多。(当数据量大的时候差距很明显)

使用with open 读取文件

# bad 
f = open('file.txt')
a = f.read()
print(a)
f.close()

# good
with open('file.txt'as f:
    for line in f:
        print(line)

参考

https://pythonguidecn.readthedocs.io/zh/latest/writing/style.html https://docs.python-guide.org/writing/style/


原文始发于微信公众号(一只大鸽子):Code Style

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/237611.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!