简体   繁体   English

python可选参数验证的可选参数

[英]python optional argument to optional argument validation

In python, how to validate optional-to-optional keyword arguments? 在python中,如何验证可选到可选的关键字参数?

this question is an extension to this question of mine about this optional-to-optional-arguments thing, (does it have a better name by the way?) 这个问题是一个扩展到这个问题,这个可选到可选的论点的东西我的,(它的方式有更好的名字吗?)

we know we can define optional arguments in this style: 我们知道我们可以用这种样式定义可选参数:

os.fdopen(fd[, mode[, bufsize]])

so that if I mistakenly call fdopen by fdopen(sth, bufsize=16) , python will point out I must specify mode to use bufsize argument. 所以如果我错误地通过fdopen(sth, bufsize=16)调用fdopen fdopen(sth, bufsize=16) ,python会指出我必须指定mode才能使用bufsize参数。

How is this implemented? 这是如何实现的? I can obviously write so much if-elseses to make this work, but that would result in some really messed-up code for those really complicated functions, for example: 显然我可以编写很多if-elseses来完成这项工作,但这会导致一些非常混乱的代码用于那些非常复杂的函数,例如:

cv2.dilate(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) → dst

There's no specific syntax for this at Python level. 在Python级别没有特定的语法。 You have to define ordinary optional arguments and do the validation yourself. 您必须定义普通的可选参数并自行进行验证。


The specific case you're looking at is implemented in C. Depending on which platform you're on, the C implementation is different. 您正在查看的具体案例在C中实现。根据您所使用的平台,C实现是不同的。 Here's the version for POSIX, Windows, and OS/2: 这是POSIX,Windows和OS / 2的版本:

static PyObject *
posix_fdopen(PyObject *self, PyObject *args)
{
    ...
    if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))
        return NULL;

The use of PyArg_ParseTuple means that this function doesn't actually accept any arguments by name. PyArg_ParseTuple的使用意味着该函数实际上并不按名称接受任何参数。 If you do os.fdopen(sth, bufsize=16) , you'll get a TypeError: 如果你执行os.fdopen(sth, bufsize=16) ,你会得到一个TypeError:

>>> os.fdopen('', bufsize=16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fdopen() takes no keyword arguments

Note that there's no real reason the bufsize argument should depend on the mode argument. 请注意, bufsize参数不应该依赖于mode参数。 I think this function probably predates keyword arguments, though it's hard to be sure. 我认为这个函数可能早于关键字参数,但很难确定。 Keyword arguments were added to Python all the way back in 1.3 , and the earliest Python documentation available on python.org is for 1.4 , by which time os.fdopen was definitely around . 关键字参数在1.3版本中一直被添加到Python ,而python.org上最早的Python文档是1.4版本 ,到那时os.fdopen肯定在

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

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