检查函数参数的最佳方法? [英] Best way to check function arguments?

查看:22
本文介绍了检查函数参数的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种有效的方法来检查 Python 函数的变量.例如,我想检查参数类型和值.有这个模块吗?或者我应该使用装饰器之类的东西,还是任何特定的习惯用法?

I'm looking for an efficient way to check variables of a Python function. For example, I'd like to check arguments type and value. Is there a module for this? Or should I use something like decorators, or any specific idiom?

def my_function(a, b, c):
    """An example function I'd like to check the arguments of."""
    # check that a is an int
    # check that 0 < b < 10
    # check that c is not an empty string

推荐答案

最 Pythonic 的习惯用法是清楚地记录函数期望什么,然后尝试使用传递给函数的任何内容,或者让异常传播或只是捕获属性错误并引发 TypeError 代替.应该尽可能避免类型检查,因为它不利于 duck-typing.价值测试可能没问题——取决于上下文.

The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError instead. Type-checking should be avoided as much as possible as it goes against duck-typing. Value testing can be OK – depending on the context.

验证真正有意义的唯一地方是系统或子系统入口点,例如 Web 表单、命令行参数等.在其他任何地方,只要您的函数被正确记录,调用者就有责任传递适当的参数.

The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.

这篇关于检查函数参数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆