函数和异常的使用实例
Function
(1)避免使用一个可变对象作为函数参数的默认值
def f(a,L=[])
L.append(a)
return L
print(f(1)) #[1]
print(f(2)) #[1,2]
print(f(3)) #[1,2,3]
得出了意想不到的结果。。。如果碰到这样的情况,估计得想破脑袋,乍看逻辑和代码都没问题
需要这么写:
def f(a,L=None)
if L is None:
L= []
L.append(a)
return L
(2)使用判断表达式来代替返回值:
harmful:
def all_equal(a,b,c):
result = False
if a==b==c:
result = True
return result
idiomatic:
def all_equal(a,b,c):
return a==b==c
(3)正确使用关键字参数
这个比较好理解也正常不会有问题,贴个例子:
Harmful:
def print_list(list_value, sep):
print('{}'.format(sep).join(list_value))
the_list = ['a', 'b', 'c']
the_other_list = ['Jeff', 'hates', 'Java']
print_list(the_list, ' ')
print_list(the_other_list, ' ')
print_list(the_other_list, ', ')
Idiomatic:
def print_list(list_value, sep=' '):
print('{}'.format(sep).join(list_value))
the_list = ['a', 'b', 'c']
the_other_list = ['Jeff', 'hates', 'Java']
print_list(the_list)
print_list(the_other_list)
print_list(the_other_list, ', ')
(4)使用* args,* * kwargs接受任意参数
def make_api_call(foo, bar, baz, *args, **kwargs):
(5)学会将函数作为值
import operator as op
for operator in (op.add, op.sub, op.mul, op.div):
print_table(operator)
(6)使用基于函数的版本的打印
Harmful:
print 1, 'foo', __name__
Idiomatic:
from __future__ import print_function #为了向3.x过度吧
print(1, 'foo', __name__)
Exceptions
(1)不要怕使用异常
(2)使用异常来写代码
def get_log_level(config_dict):
try:
if config_dict['ENABLE_LOGGING']:
return config_dict['DEFAULT_LOG_LEVEL']
except KeyError:
# if either value wasn't present, a
# KeyError will be raised, so
# return None
return None
(3)不必要抓住所有异常
import requests
def get_json_response(url):
return requests.get(url).json()
# If we need to make note of the exception, we
# would write the function this way...
def alternate_get_json_response(url):
try:
r = requests.get(url)
return r.json()
except:
# do some logging here, but don't handle the exception
# ...
raise