处理未使用的函数参数的最佳方法
Best way to handle unused function arguments
假设用户给我一个列表,其中包含可变数量的函数,这些函数具有固定数量的参数 a、b 和 c。都是固定的类型。有时会使用所有参数,但有时不会。例如:
def two_list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on each list and multiplies it by a constant.
"""
return c * (sum(a) + sum(b))
def list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on list a and multiplies it by a constant.
"""
return c * sum(a)
def list_sum_reciprocals(a: List, b: List, c: int):
""" Returns the sum of the reciprocals of each element of the list a.
"""
return sum([1/x for x in a])
用户将函数列表和参数传递给我的函数。然后,我的函数遍历所有函数,计算结果,然后用结果计算一些东西。例如:
def function_sum(functions: List, a: List, b: List, c: int):
""" Computes all the functions and adds the results.
"""
total = 0
for f in functions:
total += f(a, b, c)
return total
在不使用函数时处理函数参数的最佳方法是什么?换句话说:函数有未使用的参数是否可以,或者是否有更好的方法来完成所有这些?
保留未使用的参数是可以的,但这可能会产生误导,一些 linter 会抱怨。
另一种可以更清楚地表明未使用变量的方法是使用 _
作为变量名或在变量名前加上 _
。例如:
def two_list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on each list and multiplies it by a constant.
"""
return c * (sum(a) + sum(b))
# replace `b` with `_` or `_b`
def list_sum_mult(a: List, _, c: int):
""" Sums the elements on list a and multiplies it by a constant.
"""
return c * sum(a)
# as you only care about the first argument you can ignore the others with `*_`
def list_sum_reciprocals(a: List, *_):
""" Returns the sum of the reciprocals of each element of the list a.
"""
return sum([1/x for x in a])
可以有未使用的参数,你可以让这些参数有一个默认值
假设用户给我一个列表,其中包含可变数量的函数,这些函数具有固定数量的参数 a、b 和 c。都是固定的类型。有时会使用所有参数,但有时不会。例如:
def two_list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on each list and multiplies it by a constant.
"""
return c * (sum(a) + sum(b))
def list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on list a and multiplies it by a constant.
"""
return c * sum(a)
def list_sum_reciprocals(a: List, b: List, c: int):
""" Returns the sum of the reciprocals of each element of the list a.
"""
return sum([1/x for x in a])
用户将函数列表和参数传递给我的函数。然后,我的函数遍历所有函数,计算结果,然后用结果计算一些东西。例如:
def function_sum(functions: List, a: List, b: List, c: int):
""" Computes all the functions and adds the results.
"""
total = 0
for f in functions:
total += f(a, b, c)
return total
在不使用函数时处理函数参数的最佳方法是什么?换句话说:函数有未使用的参数是否可以,或者是否有更好的方法来完成所有这些?
保留未使用的参数是可以的,但这可能会产生误导,一些 linter 会抱怨。
另一种可以更清楚地表明未使用变量的方法是使用 _
作为变量名或在变量名前加上 _
。例如:
def two_list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on each list and multiplies it by a constant.
"""
return c * (sum(a) + sum(b))
# replace `b` with `_` or `_b`
def list_sum_mult(a: List, _, c: int):
""" Sums the elements on list a and multiplies it by a constant.
"""
return c * sum(a)
# as you only care about the first argument you can ignore the others with `*_`
def list_sum_reciprocals(a: List, *_):
""" Returns the sum of the reciprocals of each element of the list a.
"""
return sum([1/x for x in a])
可以有未使用的参数,你可以让这些参数有一个默认值