Python 最佳实践指南

粗粗粗略地过了一遍,大体捞了一些东西出来,大段大段英文太费眼了,回头细读在更新进来

浓缩版,20分钟可大体过完,然后根据自己需要去看详细的吧

整体内容还是很不错的,建议细读英文

PS:文档含有巨量的TODO(没写空白着待补充的),不过但从目录上来看还是很强大滴,相信完善后,会成为一份很牛逼的指南(难度比官方指南高一点点)


第零部分 Getting Started

链接

不解释,不翻译,自个看….真的没啥(每本入门书籍第一章…)


第一部分 Writing Great Code

Structuring Your Project

链接

import 最佳实践

Very bad

1

2

3

4

[...]

from modu import *

[...]

x = sqrt(4)  # Is sqrt part of modu? A builtin? Defined above?

Better

1

2

3

from modu import sqrt

[...]

x = sqrt(4)  # sqrt may be part of modu, if not redefined in between

Best

1

2

3

import modu

[...]

x = modu.sqrt(4)  # sqrt is visibly part of modu‘s namespace

Python中关于OOP的 观点

Decorators

1

2

3

4

5

6

7

8

9

10

11

12

13

def foo():

# do something

def decorator(func):

# manipulate func

return func

foo = decorator(foo)  # Manually decorate

@decorator

def bar():

# Do something

# bar() is decorated

动态类型(Dynamic typing)

Avoid using the same variable name for different things.

Bad

1

2

3

4

a = 1

a = ‘a string‘

def a():

pass  # Do something

Good

1

2

3

4

count = 1

msg = ‘a string‘

def func():

pass  # Do something

It is better to use different names even for things that are related, when they have a different type:

1

2

3

4

5

Bad

items = ‘a b c d‘  # This is a string...

items = items.split(‘ ‘)  # ...becoming a list

items = set(items)  # ...and then a set

可变和不可变类型(Mutable and immutable types)

字符串拼接最佳实践

Bad

1

2

3

4

5

# create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = ""

for n in range(20):

nums += str(n)   # slow and inefficient

print nums

Good

1

2

3

4

5

# create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = []

for n in range(20):

nums.append(str(n))

print "".join(nums)  # much more efficient

Best

1

2

3

# create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = [str(n) for n in range(20)]

print "".join(nums)

join() is not always best
创建新字符串和修改原有字符串

1

2

3

4

5

6

foo = ‘foo‘

bar = ‘bar‘

foobar = foo + bar  # This is good

foo += ‘ooo‘  # This is bad, instead you should do:

foo = ‘‘.join([foo, ‘ooo‘])

字符串格式化

1

2

3

4

5

6

foo = ‘foo‘

bar = ‘bar‘

foobar = ‘%s%s‘ % (foo, bar) # It is OK

foobar = ‘{0}{1}‘.format(foo, bar) # It is better

foobar = ‘{foo}{bar}‘.format(foo=foo, bar=bar) # It is best

Code Style

链接

一般概念(General concepts)

明确的代码

Bad

1

2

3

def make_complex(*args):

x, y = args

return dict(**locals())

Good

1

2

def make_complex(x, y):

return {‘x‘: x, ‘y‘: y}

每行一个声明

Bad

1

2

3

4

5

6

print ‘one‘; print ‘two‘

if x == 1: print ‘one‘

if  and :

# do something

Good

1

2

3

4

5

6

7

8

9

10

print ‘one‘

print ‘two‘

if x == 1:

print ‘one‘

cond1 =

cond2 =

if cond1 and cond2:

# do something

函数参数

1

2

#不解释了

位置参数,默认参数,*args, **args

Avoid the magical wand(这个肿么翻…)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

原因:

Python comes with a very rich set of hooks and tools allowing to do almost any kind of tricky tricks

建议:

it is always better to use the most straightforward way to achieve your goal

感受一下:

We consider that a Python developer should know about these nearly infinite possibilities,

because it grows the confidence that no hard-wall will be on the way.

However, knowing how to use them and particularly when not to use them is the most important.

Like a Kungfu master, a Pythonista knows how to kill with a single finger, and never to actually do it.

其实就是告诉你,骚年,这玩意你要去学习去了解去掌握,目的是增强实力保持自信,但是不要去用啊

(说的原子弹吧....)

方言(Idioms)

Idiomatic Python code is often referred to as being Pythonic.

列举了一些:

Unpacking

1

2

3

4

5

6

for index, item in enumerate(some_list):

# do something with index and item

a, b = b, a

a, (b, c) = 1, (2, 3)

忽略接收变量,这里用的是两个下划线,原因

http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable

1

2

filename = ‘foobar.txt‘

basename, __, ext = filename.rpartition(‘.‘)

同一个元素创建一个长度为N的列表

1

four_nones = [None] * 4

创建一个长度N的嵌套列表

1

four_lists = [[] for __ in xrange(4)]

由列表拼接字符串

1

2

letters = [‘s‘, ‘p‘, ‘a‘, ‘m‘]

word = ‘‘.join(letters)

快速查找

1

2

3

4

5

6

7

8

d = {‘s‘: [], ‘p‘: [], ‘a‘: [], ‘m‘: []}

l = [‘s‘, ‘p‘, ‘a‘, ‘m‘]

def lookup_dict(d): #O(1)

return ‘s‘ in d

def lookup_list(l): #O(n)

return ‘s‘ in l

Zen of Python

1

import this

PEP8

1

2

3

4

$ pip install pep8

$ pep8 optparse.py

optparse.py:69:11: E401 multiple imports on one line

optparse.py:77:1: E302 expected 2 blank lines, found 1

惯例(Conventions)

判断值是否等于常量

Bad:

1

2

3

4

5

if attr == True:

print ‘True!‘

if attr == None:

print ‘attr is None!‘

Good:

1

2

3

4

5

6

7

8

9

10

11

# Just check the value

if attr:

print ‘attr is truthy!‘

# or check for the opposite

if not attr:

print ‘attr is falsey!‘

# or, since None is considered false, explicitly check for it

if attr is None:

print ‘attr is None!‘

获取字典元素

Bad:

1

2

3

4

5

d = {‘hello‘: ‘world‘}

if d.has_key(‘hello‘):

print d[‘hello‘]    # prints ‘world‘

else:

print ‘default_value‘

Good:

1

2

3

4

5

6

7

8

d = {‘hello‘: ‘world‘}

print d.get(‘hello‘, ‘default_value‘) # prints ‘world‘

print d.get(‘thingy‘, ‘default_value‘) # prints ‘default_value‘

# Or:

if ‘hello‘ in d:

print d[‘hello‘]

快捷列表操作

Bad:

1

2

3

4

5

6

# Filter elements greater than 4

a = [3, 4, 5]

b = []

for i in a:

if i > 4:

b.append(i)

Good:

1

2

3

a = [3, 4, 5]

b = [i for i in a if i > 4]

b = filter(lambda x: x > 4, a)

Bad:

1

2

3

4

# Add three to all list members.

a = [3, 4, 5]

for i in range(len(a)):

a[i] += 3

Good:

1

2

3

4

a = [3, 4, 5]

a = [i + 3 for i in a]

# Or:

a = map(lambda i: i + 3, a)

使用enumerate

1

2

3

4

5

6

for i, item in enumerate(a):

print i, item

# prints

# 0 3

# 1 4

# 2 5

读文件

Bad:

1

2

3

4

f = open(‘file.txt‘)

a = f.read()

print a

f.close()

Good:

1

2

3

with open(‘file.txt‘) as f:

for line in f:

print line

超长的行

Bad:

1

2

3

4

5

6

my_very_big_string = """For a long time I used to go to bed early. Sometimes,

when I had put out my candle, my eyes would close so quickly that I had not even

time to say “I’m going to sleep.”"""

from some.deep.module.inside.a.module import a_nice_function, another_nice_function,

yet_another_nice_function

Good:

1

2

3

4

5

6

7

8

9

#受教了....

my_very_big_string = (

"For a long time I used to go to bed early. Sometimes, "

"when I had put out my candle, my eyes would close so quickly "

"that I had not even time to say “I’m going to sleep.”"

)

from some.deep.module.inside.a.module import (

a_nice_function, another_nice_function, yet_another_nice_function)

Reading Great Code

链接

感受下:The number one thing that Python programmers do is read code.

再感受一把:One of the secrets of becoming a great Python programmer is to read, understand, and comprehend excellent code.

几个推荐阅读源代码项目

Howdoi

Flask

Werkzeug

Requests

Tablib

文档(Documentation)

链接

感受一下:Readability is a primary focus for Python developers, in both project and code documentation.

具体还是读原文吧

项目文档组成

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1.A README file

at the root directory should give general information to the users and the maintainers.

reStructuredText 或 Markdown

2.An INSTALL file

is less necessary with python

setup.py

3.A LICENSE file

should always be present and specify the license under which the software is made available to the public

4.A TODO file or a TODO section in README

should list the planned development for the code.

5.A CHANGELOG file or section in README

should compile a short overview of the changes in the code base for the latest versions.

几种文档工具

1

2

3

Sphinx(听说最强大....)

reStructuredText

Markdown(俺的最爱...)

代码文档建议

Comments clarify code and begin with a hash (#).

In Python, docstrings describe modules, classes, and functions:

1

2

def square_and_rooter(x):

"""Returns the square root of self times self."""

注解代码块

Do not use triple-quote strings to comment code.

This is not a good practice, because line-oriented command-line tools such as grep will not be aware that the commented code is inactive.

It is better to add hashes at the proper indentation level for every commented line.

最佳实践:

1

2

不用三引号注解代码块

每一行加#来注释

测试你的代码(Testing Your Code)

链接

测试一些通用原则

1

2

3

4

5

6

7

8

9

10

11

12

13

1.A testing unit should focus on one tiny bit of functionality and prove it correct.

2.Each test unit must be fully independent

3.Try hard to make tests that run fast

4.Learn your tools and learn how to run a single test or a test case

5.Always run the full test suite before a coding session, and run it again after.

6.It is a good idea to implement a hook that runs all tests before pushing code to a shared repository.

7.If you are in the middle of a development session and have to interrupt your work,

it is a good idea to write a broken unit test about what you want to develop next.

8.The first step when you are debugging your code is to write a new test pinpointing the bug.

9.Use long and descriptive names for testing functions

10.When something goes wrong or has to be changed, and if your code has a good set of tests,

you or other maintainers will rely largely on the testing suite to fix the problem or modify a given behavior.

11.Another use of the testing code is as an introduction to new developers.

单元测试(Unittest)

Python内置模块, 文档

1

2

3

4

5

6

7

8

import unittest

def fun(x):

return x + 1

class MyTest(unittest.TestCase):

def test(self):

self.assertEqual(fun(3), 4)

文档测试(Doctest)

非精细case,只验证主体功能可用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def square(x):

"""Squares x.

>>> square(2)

4

>>> square(-2)

4

"""

return x * x

if __name__ == ‘__main__‘:

import doctest

doctest.testmod()

相关工具

py.text
$ pip install pytest

Nose unittest的扩展
$ pip install nose

tox
$ pip install tox

Unittest2
$ pip install unittest2

mock
$ pip install mock

Common Gotchas(不懂怎么翻…╮(╯▽╰)╭ )

一些新手可能疑惑的例子

两个例子

1.可变默认参数

What You Wrote

1

2

3

def append_to(element, to=[]):

to.append(element)

return to

What You Might Have Expected to Happen

1

2

3

4

5

6

7

8

my_list = append_to(12)

print my_list

my_other_list = append_to(42)

print my_other_list

[12]

[42]

What Does Happen

1

2

[12]

[12, 42]

What You Should Do Instead

1

2

3

4

5

def append_to(element, to=None):

if to is None:

to = []

to.append(element)

return to

Python默认参数在函数定义处执行一次,而不是每次函数调用时执行。

2.Late Binding Closures(又一个,延迟绑定闭包?)

What You Wrote

1

2

def create_multipliers():

return [lambda x : i * x for i in range(5)] #

What You Might Have Expected to Happen

1

2

3

4

5

6

7

8

for multiplier in create_multipliers():

print multiplier(2) # 任意一个返回的函数被调用时,内部循环i=4

0

2

4

6

8

What Does Happen

1

2

3

4

5

8

8

8

8

8

What You Should Do Instead

1

2

3

4

5

from functools import partial

from operator import mul

def create_multipliers():

return [partial(mul, i) for i in range(5)]

Python的闭包是延时绑定

选择证书(Choosing a License)

链接

开源证书 列表

证书选择器 入口


第二部分 Scenario Guide

都是介绍性质的,类似工具目录,而且大部分是空的,目前没详细信息

要了解具体,goole相关关键词吧

具体自己翻吧 位置

目录:

Network Applications

Http:

1

Requests

Distributed Systems

1

2

ZeroMQ

RabbitMQ

Web Applications

Context

1

WSGI

Frameworks

1

2

3

4

5

Django

Flask

Werkzeug

Tornado

Pyramid

Web Servers

1

Nginx

WSGI Servers

1

Gunicorn

Hosting

1

2

3

4

PasS (Platform as a service)

Heroku

DotCloud

Gondor

Templating

1

Jinja2

HTML Scraping

1

2

lxml

Requests

Command Line Applications

1

2

Clint

docopt

GUI Applications

1

2

3

4

5

6

7

8

Qt

Cocoa

wxPython

GTk

Tk

Kivy

PyjamasDesktop (pyjs Desktop)

Camelot

Databases

1

2

3

DB-API

SQLAlchemy

Django ORM

Networking

1

2

3

Twisted

PyZMQ

gevent

Systems Administration

1

2

3

4

5

6

7

Fabric

Salt

Psutil

Chef

Puppet

Blueprint

Buildout

Continuous Integration

1

2

3

4

5

Jenkins

Buildbot

Mule?

Tox

Travis-CI

Speed

C Extensions

1

2

3

4

5

GIL

Cython

Pyrex

Shedskin

Numba

Threading

1

2

Threading

Multiprocessing

Scientific Applications

Tools

1

IPython

Libraries

1

2

3

4

5

6

7

NumPy

Numba

SciPy

Matplotlib

Pandas

Rpy2

PsychoPy

Image Manipulation

1

Python Imaging Library(PIL)

XML parsing

1

2

untangle

xmltodict

QQ群290551701 聚集很多互联网精英,技术总监,架构师,项目经理!开源技术研究,欢迎业内人士,大牛及新手有志于从事IT行业人员进入!

时间: 2024-10-11 22:57:24

Python 最佳实践指南的相关文章

PYTHON 最佳实践指南(转)

add by zhj: 本文参考了The Hitchhiker's Guide to Python,当然也加入了作者的一些东西.The Hitchhiker's Guide to Python 的github地址是https://github.com/kennethreitz/python-guide,貌似还能用pip安装该包.先占个坑,后面有时间再把文章转过来 原文:PYTHON 最佳实践指南

20个设计数据库的最佳实践指南

数据库设计看上去很简单,但是如果不经意随意设计,可能会为日后维护拓展或性能方面埋下祸根.以下是20个设计数据库的最佳实践指南: 1. 使用完整的一致的数据表名称和字段名,如:School, StudentCourse, CourseID 2.数据表名称使用单数,比如使用StudentCourse 而不是StudentCourses,数据表代表实体的一个集合,因此没有必要使用复数名称. 3. 数据表名称不要使用空格,比如StudentCourse 比Student Course更好. 4.数据表名

分享《Python机器学习实践指南》(高清中文版PDF+高清英文版PDF+源代码)

下载:https://pan.baidu.com/s/11dGldpITOoUUJmS9eD5ENw Python机器学习实践指南(高清中文版PDF+高清英文版PDF+源代码) 中文和英文两版对比学习, 带目录书签,可复制粘贴:讲解详细并配有源代码. 其中,高清中文版如图: 原文地址:http://blog.51cto.com/3215120/2301528

分享《Python机器学习实践指南》+PDF+源码+Alexanfer T.Combs+黄申

下载:https://pan.baidu.com/s/1nb-Q7MtQ2dfBbx2Dir-rQA 更多资料分享:http://blog.51cto.com/14087171 Python机器学习实践指南(高清中文版PDF+高清英文版PDF+源代码) 高清中文版PDF,268页,带目录书签,彩色配图,文字可复制粘贴: 高清英文版PDF,324页,带目录书签,彩色配图,文字可复制粘贴: 中文和英文两版对比学习: 讲解详细并配有源代码. 其中,高清中文版如图: 原文地址:http://blog.5

机器学习实践:《Python机器学习实践指南》中文PDF+英文PDF+代码

机器学习是近年来渐趋热门的一个领域,同时Python 语言经过一段时间的发展也已逐渐成为主流的编程语言之一.<Python机器学习实践指南>结合了机器学习和Python 语言两个热门的领域,通过利用两种核心的机器学习算法来将Python 语言在数据分析方面的优势发挥到极致. 共有10 章.第1 章讲解了Python 机器学习的生态系统,剩余9 章介绍了众多与机器学习相关的算法,包括各类分类算法.数据可视化技术.推荐引擎等,主要包括机器学习在公寓.机票.IPO 市场.新闻源.内容推广.股票市场.

[转]ASP.NET Core Web API 最佳实践指南

原文地址: ASP.NET-Core-Web-API-Best-Practices-Guide 转自 介绍# 当我们编写一个项目的时候,我们的主要目标是使它能如期运行,并尽可能地满足所有用户需求. 但是,你难道不认为创建一个能正常工作的项目还不够吗?同时这个项目不应该也是可维护和可读的吗? 事实证明,我们需要把更多的关注点放到我们项目的可读性和可维护性上.这背后的主要原因是我们或许不是这个项目的唯一编写者.一旦我们完成后,其他人也极有可能会加入到这里面来. 因此,我们应该把关注点放到哪里呢? 在

Python 最佳实践

前言 对我来说,以前每次面试是我审视自己,检验自己的一种方式.每次准备面试,以及被面试官问住的时候才会发现,其实我python我学的还不够好.工作中也是,可以从其他的同事那里获得成长.但是我今天说的是,我也在自己总结和思考最佳实践这件事. 我想很多人都会有意识的去读一些PEP(Python Enhancement Proposals).了解语言设计者当时的考虑,这些文案也是经过很长时间的讨论最后才实施的.既然想用好这门语言,必然需要理解设计之美.比如我听说gvanrossum使用emacs作为编

ASP.NET Core Web API 最佳实践指南

https://www.cnblogs.com/hippieZhou/p/11966373.html 原文地址: ASP.NET-Core-Web-API-Best-Practices-Guide 原文地址:https://www.cnblogs.com/94cool/p/12388416.html

Artifactory 仓库架构和命名最佳实践(下)

在上篇文章中,我们已经建立了基本的仓库命名结构,在 JFrog Artifactory 中,仓库管理的最佳实践应该考虑三个因素:安全性,性能和可操作性.大多数情况下,这些因素跟你的团队规模密切相关,在较小程度上跟仓库成熟度等级的粒度划分有一定的关系. 安全 Artifactory 允许通过包含/排除模式在单个文件夹甚至文件级别进行管理权限.一般来说,这里的最佳做法是在仓库级别管理权限.对于具有高度结构化的仓库(如 Maven 和 RPM),可以在文件夹级别实现细粒度的控制.但是,对于管理员来说,