Best Practices Guide for Python reading notes

0-19 will create a string of connected

1
2
3
4
5
6
7
8
nums = []
for n in range(20):
nums.append(str(n))
print "".join(nums)

# Better written
the nums = [STR (n-) for n-in Range (20 is)]
Print "" .join (the nums)

More than stitching string

1
2
3
4
5
6
7
foo = 'foo'
bar = 'bar'

foobar = foo + bar # good practice

foo + = 'ooo' # bad practice, should do:
foo = '' .join ([foo, 'OOO'])

You can also use % format operator to determine the number of connected strings, but PEP 3101 recommended str.format () Alternatively% operators.

1
2
3
4
5
6
foo = 'foo'
bar = 'bar'

foobar = '% s% s' % (foo, bar) # viable
foobar = '{0} {1 }'. format (foo, bar) # better
foobar = '{foo} {bar }'. format (foo = foo, bar = bar) # best

Do not reuse named

1
2
3
items = 'abcd' # first to a string ... 
items items.split = ( '') # ... becomes a listing
items = set (items) # ... and then into the collection

Named for re-use and efficiency did not improve: in any case the assignment to create a new object. However, with the enhancement of the complexity of the assignment statement is separated from other code including 'if' branch and loop, making it more difficult to identify the type of the specified variable. In practice some code, such as functional programming, is recommended to never repeat the same variable name assignment. Implementation is to use Java in the 'final' keyword. Python is not 'final' keyword and this is contrary to its philosophy. Nevertheless, to avoid repeating the same variable name assignment is still a good practice and helps to grasp the concept of variable and immutable type.

This should not consider any list of parameters with (* args)

If the function accepts a list of parameters having the same properties, it is generally defined as a parameter, which is a list or any other sequence will be clearer.

Single export function may be better

When a function has a number of major exit points in its normal course, it will become difficult to debug and returns its result, so keep a single exit point could be better. This will also help extract some code paths, and multiple exit points means that there is likely to require reconstruction.

1
2
3
4
5
6
7
8
9
10
11
complex_function DEF (A, b, c): 
IF not A:
return None # throws an exception might be better
IF not b:
return None # throws an exception might be better

# Some complex code try a, b, c to calculate x
# if successful, resisted the temptation to return x
IF not x:
# something about the calculation of the x-B Plan
return x

Common Python idioms

  • Unpack
1
2
3
4
5
6
index for, item in the enumerate (some_list): 
# use the index and do some work item a, b = b, a



a, (b, c) = 1, (2, 3)
  • Create a variable to be ignored
1
2
filename = 'foobar.txt'
basename, __, ext = filename.rpartition('.')
  • Creating a list of objects containing N
1
four_nones = [None] * 4
  • Create a list containing a list of N
1
four_lists = [[] for __ in xrange(4)]
  • To create a string from a list
1
2
letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)
  • Find an item in the collection (collection) in
1
2
3
4
5
6
7
8
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

In the following cases the use of collection or dictionary instead of a list, usually a good idea:

Collection contains a large number of items
you will find duplicate items in the aggregate
you do not have duplicate entries

You do not need to explicitly compare a value is True, or None, or 0

bad

1
2
3
4
5
if attr == True:
print 'True!'

if attr == None:
print 'attr is None!'

优雅

1
2
3
4
5
6
7
8
9
10
11
# 检查值
if attr:
print 'attr is truthy!'

# 或者做相反的检查
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!'

访问字典元素

糟糕

1
2
3
4
5
d = {'hello': 'world'}
if d.has_key('hello'):
print d['hello'] # 打印 'world'
else:
print 'default_value'

优雅

1
2
3
4
5
6
7
8
d = {'hello': 'world'}

print d.get('hello', 'default_value') # 打印 'world'
print d.get('thingy', 'default_value') # 打印 'default_value'

# Or:
if 'hello' in d:
print d['hello']

在每次函数调用中,通过使用指示没有提供参数的默认参数 None 通常是 个好选择),来创建一个新的对象。

举例:

1
2
3
def append_to(element, to=[]):
to.append(element)
return to

你可能认为

1
2
3
4
5
my_list = append_to(12)
print my_list # [12]

my_other_list = append_to(42)
print my_other_list # [42]

实际结果为

1
2
3
# [12]

# [12, 42]

当函数被定义时,一个新的列表就被创建一次 ,而且同一个列表在每次成功的调用中都被使用。

当函数被定义时,Python的默认参数就被创建 一次,而不是每次调用函数的时候创建。 这意味着,如果你使用一个可变默认参数并改变了它,你 将会 在未来所有对此函数的 调用中改变这个对象。

迟绑定闭包

举例

1
2
3
4
5
def create_multipliers():
return [lambda x : i * x for i in range(5)]

for multiplier in create_multipliers():
print multiplier(2)

你期望的结果

1
2
3
4
5
0
2
4
6
8

实际结果

1
2
3
4
5
8
8
8
8
8

五个函数被创建了,它们全都用4乘以 x 。

Python的闭包是 迟绑定 。 这意味着闭包中用到的变量的值,是在内部函数被调用时查询得到的。

这里,不论 任何 返回的函数是如何被调用的, i 的值是调用时在周围作用域中查询到的。 接着,循环完成, i 的值最终变成了4。

这个陷阱并不和 lambda 有关,不通定义也会这样

1
2
3
4
5
6
7
8
9
def create_multipliers():
multipliers = []

for i in range(5):
def multiplier(x):
return i * x
multipliers.append(multiplier)

return multipliers

solution

The most common solution can be said to be a bit tricky (hack). Because Python has a default parameter assignment as a function of behavior, you can create an immediate closure of a binding parameter, like this:

1
2
def create_multipliers():
return [lambda x, i=i : i * x for i in range(5)]

Alternatively, a function.partialfunction

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)]

Original: Big Box  Best Practices Guide for Python reading notes


Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11618234.html