繁体   English   中英

仅将参数传递给 function 如果需要该参数 Python

[英]Only pass an argument to a function if it takes that argument Python

我有一个“验证”方法,它的工作原理如下:

def validate(self, allow_deferred_fields=False):
    """
    Validate the data in the group.
    Raises ValidationError if there is any incorrect data.
    """
    # Check custom validation of current group
    self.custom_validation()

并且 custom_validation 方法根据正在验证的组而有所不同。 我的 custom_validation 定义之一我想像这样传递参数“allow_deferred_fields”:

def custom_validation(self, allow_deferred_fields=False):
    if allow_deferred_fields:
    .... some code

但其他 custom_validation 方法不采用此参数。 如何将此参数传递给 validate 方法中的 custom_validation 调用,而不必将其作为参数添加到它可能调用的所有其他 custom_validation 方法?

这是一个设计问题。 目前, validate的“合同”的一部分是它将调用一个方法custom_validation ,arguments 为零。 您需要更改validate以接受额外的 arguments 以传递:

def validate(self, *args, **kwargs):
    self.custom_validation(*args, **kwargs)

或者您需要在 object 本身中“嵌入”该标志,以便custom_validation在调用时可以访问它。

def validate(self):
    self.custom_validation()

def custom_validation(self):
    if self.allow_deferred_fields:
        ...

...
obj.allow_deferred_fields = True
obj.validate()

不过,第二个选项有点小技巧。 这并不比拥有一个custom_validation检查的全局变量好多少。

第三个选项是强制所有自定义验证方法在validate调用时接受(可能是任意的)关键字 arguments ,尽管它们可以随意忽略该参数。

在这种情况下,很难检查 function 是否采用参数(请参阅inspect.signature),但调用 function 并在它不支持该参数时捕获错误非常容易,只要您知道 ZC1C425268E173永远不要引发 TypeError

这还具有使用基于 C 的函数的优点。

def validate(self, allow_deferred_fields=False):
    """
    Validate the data in the group.
    Raises ValidationError if there is any incorrect data.
    """
    # Check custom validation of current group
    try:
        self.custom_validation(allow_deferred_fields=True)
    except TypeError:
        self.custom_validation()

如果您不能依赖 function 永远不会抛出 TypeError,您可以尝试以下操作,但请记住,如果 function 在 Z0D61F8370CAD1D4122F570B84D143E 中实现,它将失败

def validate(self, allow_deferred_fields=False):
    """
    Validate the data in the group.
    Raises ValidationError if there is any incorrect data.
    """
    # Check custom validation of current group
    if "allow_deferred_fields" in inspect.signature(self.custom_validation):
        self.custom_validation(allow_deferred_fields=True)
    else:
        self.custom_validation()

暂无
暂无

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

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