简体   繁体   English

将函数作为命名参数传递以进行条件检查

[英]Passing a function as a named argument for conditional checking

def basket(name, colour, smell, rotten=None):
    if rotten:
        if rotten():
            return "Can't eat!"

    return ("The fruit, {}, is {} in colour"
            "and smells like {}.".format(name, colour, smell))

In the example code above, the argument rotten , if provided, is checked before calling.在上面的示例代码中,参数rotten ,如果提供的话,在调用之前被检查。 It must be a function that returns a boolean (no arguments for simplicity).它必须是一个返回布尔值的函数(为简单起见,没有参数)。 It consumes two lines of code and I'm not certain if this is the conventional style for this procedure.它消耗两行代码,我不确定这是否是此过程的常规样式。 Another way I thought of doing it was to replace the current one with:我想到的另一种方法是将当前的替换为:

def basket(name, colour, smell, rotten=lambda: None):
    if rotten():  # Saved a line here
        return "Can't eat!"

    return ("The fruit, {}, is {} in colour"
            " and smells {}.".format(name, colour, smell))

The lambda method saves one line; lambda 方法节省了一行; apart from that I don't know which one has the advantage over the other.除此之外,我不知道哪一个比另一个有优势。 What is the preferable way of doing this?这样做的最佳方法是什么? Is it found anywhere in the standard library code?在标准库代码的任何地方都可以找到它吗?

You can leave the function signature intact as in your first example and take advantage of boolean operations's short circuit behavior to turn it into one line like this:您可以像第一个示例一样保持函数签名不变,并利用布尔运算的短路行为将其变成这样的一行:

def basket(name, colour, smell, rotten=None):
    if rotten and rotten():
        return "Can't eat!"

    return ("The fruit, {}, is {} in colour"
            "and smells like {}.".format(name, colour, smell))

If rotten is None , the and expression will fail without calling rotten() because of short circuit.如果rottenNone ,由于短路, and表达式将失败而不调用rotten() If rotten is not None , it will proceed to call rotten() and will succeed the predicate is True .如果rotten不是None ,它将继续调用rotten()并将成功谓词为True

Note: As mentioned in the comments, you can also use the function callable() and check if rotten can be called before actually calling it:注意:如评论中所述,您还可以使用函数callable()并在实际调用之前检查是否可以调用rotten

if callable(rotten) and rotten():

This will protect your function from rising an exception when rotten is not None but is not a callable object (passing rotten=True for example).rotten不是None但不是可调用对象(例如传递rotten=True )时,这将保护您的函数免于引发异常。 If otherwise you prefer the function to complaint out loud when a non callable is passed, then just let it as it is.如果否则您更喜欢函数在传递不可调用时大声抱怨,那么就让它原样。

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

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