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

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

问题描述

我正在寻找一种检查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

推荐答案

最Python化的习惯用法是清楚地 document 该函数期望什么,然后尝试使用传递给该函数的任何东西,或者让异常传播或仅捕获属性错误并改为引发TypeError.应尽可能避免类型检查,因为这与鸭式打字不符.视情况而定,可以进行价值测试.

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天全站免登陆