首页 > 解决方案 > 检查参数是否在不检查值的情况下传递给函数

问题描述

我不确定这在 Python 中是否可行,我想知道,是否有任何方法可以在运行时检查参数是否传递给 Python 函数而不对参数值进行某种检查?

def my_func(req, opt=0):
    return was_opt_passed() # Returns bool 

print(my_func(0)) # Prints False
print(my_func(0, 0)) # Prints True

如果可能的话,这在某些情况下会更好,因为它消除了记住和检查哨兵值的需要。可能吗?

标签: pythonpython-3.xfunctionparameter-passing

解决方案


正如马克在他的评论中已经说过的,典型的约定是使用默认值None。然后你可以检查它是否仍然None在调用。

def my_func(req, opt=None):
    if opt is None:
        #opt wasn’t passed.
        return False
    #opt was passed
    return True

尽管如果您想对其他选项进行更多研究(大多数情况下最不合常规),请随时查看这些答案


推荐阅读