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
Decorators
The Python language provides a simple yet powerful syntax called ‘decorators’. A decorator is a function or a class that wraps (or decorates) a function or a method. The ‘decorated’ function or method will replace the original ‘undecorated’ function or method. Because functions are first-class objects in Python, this can be done ‘manually’, but using the @decorator syntax is clearer and thus preferred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def foo():
# do something
def decorator(func):
# manipulate func
return func
foo = decorator(foo) # Manually decorate
@decorator
def bar():
# Do something
# bar() is decorated
Bad
1
2
3
items = 'a b c d' # This is a string...
items = items.split(' ') # ...becoming a list
items = set(items) # ...and then a set
Good
1
2
3
4
count = 1
msg = 'a string'
def func():
pass # Do something
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")
近期评论