《effective python》- python默认参数
1 import json 2 import time 3 from datetime import datetime 4 5 6 def print_log(msg: str, when=None): 7 when = datetime.now() if when is None else when 8 print(f'time:{when} print msg:{msg}') 9 10 11 print_log('msg') 12 time.sleep(5) 13 print_log('msg') 14 15 16 def decode(data: str, default={}): 17 try: 18 return json.loads(data) 19 except ValueError: 20 return default 21 22 23 foo = decode('bad data') 24 foo['stuff'] = 5 25 bar = decode('also bad') 26 bar['meep'] = 1 27 print(f'foo:{foo}') 28 print(f'bar:{bar}') 29 30 31 def decode_v2(data: str, default=None): 32 default = {} if default is None else default 33 try: 34 return json.loads(data) 35 except ValueError: 36 return default 37 38 foo = decode_v2('bad data') 39 foo['stuff'] = 5 40 bar = decode_v2('also bad') 41 bar['meep'] = 1 42 print(f'foo:{foo}') 43 print(f'bar:{bar}')
Please call me JiangYouDang!
