Optional python argument for optional argument verification

In python, how to check optional keyword arguments optionally?

this question is an extension of this question of my question about this optional-optional argumentation (by the way, does he have a better name?)

we know that we can define optional arguments in this style:

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

so if I mistakenly call fdopenon fdopen(sth, bufsize=16), python will indicate what I must indicate in modeorder to use the argument bufsize.

How is this implemented? I obviously can write so many if-elseses to do this work, but this will lead to some really messed up code for these really complex functions, like this:

cv2.dilate(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) β†’ dst
+4
source share
1 answer

There is no special syntax for this at the Python level. You must define the usual optional arguments and perform the validation yourself.


The specific case you are looking at is implemented in C. Depending on which platform you are running on, the implementation of C is different. Here is the version for POSIX, Windows and OS / 2:

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

Use PyArg_ParseTuplemeans that this function does not actually accept any arguments by name. If you execute os.fdopen(sth, bufsize=16), you will get a TypeError:

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

, , bufsize mode. , , , , . Python 1.3, Python, python.org, 1.4, os.fdopen .

+2

Source: https://habr.com/ru/post/1620957/


All Articles