我在某处读到函数应该总是只返回一种类型,所以下面的代码被认为是坏代码:
def x(foo):
if 'bar' in foo:
return (foo, 'bar')
return None
Run Code Online (Sandbox Code Playgroud)
我想更好的解决方案是
def x(foo):
if 'bar' in foo:
return (foo, 'bar')
return ()
Run Code Online (Sandbox Code Playgroud)
返回一个None然后创建一个新的空元组不是更便宜的记忆吗?或者这个时间差太小而不能注意到即使在较大的项目中?