繁体   English   中英

Python:参数类型为function时如何设置默认值?

[英]Python: How to set the default value when the parameter type is function?

我正在修改一个 function,它已经有一些具有默认值的参数。

我需要将 function 作为参数,它应该有一个默认值,应该类似于None ,这样我就可以避免在未设置时使用它。

下面是一个简单的例子,实际上None不应该使用。

from collections.abc import Callable

def myfunc(x: int=0, metric_func: Callable=None):
    '''Type "None" cannot be assigned to type "function"'''
    ret = []
    if metric_func == None:
        return ret

    for i in range(10):
        ret.append(metric(x, i))
    return ret

def dot(x, y):
    return x * y

if __name__ == "__main__":
    myfunc(1, dot)

只要查看标准库,您就会使用最常见的方法。

例如在heapq (1) (2) (3) , bisect (1) (2) , itertools (1)中:

def merge(*iterables, key=None, reverse=False):
    '''Merge multiple sorted inputs into a single sorted output.

    Similar to sorted(itertools.chain(*iterables)) but returns a generator,
    does not pull the data into memory all at once, and assumes that each of
    the input streams is already sorted (smallest to largest).

    >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
    [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]

    If *key* is not None, applies a key function to each element to determine
    its sort order.

    >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
    ['dog', 'cat', 'fish', 'horse', 'kangaroo']

    '''

    # skipping some lines

    if key is None:
        ...

    # skipping the rest

如果你想明确地输入它,只需用Union[Callable, None]Callable | None创建一个Union 如果使用Callable | None >= 3.10,则无。

您应该检查Nonev is None而不是v == None

如果可能,请键入您的Callable ,否则它默认为Callable[..., Any]

最后,如果可能的话,在我放置<idk>标记的地方输入你的返回值。

def myfunc(x: int = 0, metric_func: Callable[[int, int], <idk>] | None = None) -> list[<idk>]:
    '''Type "None" cannot be assigned to type "function"'''
    ret = []
    if metric_func is None:
        return ret

    for i in range(10):
        ret.append(metric_func(x, i))
    return ret

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM