timfeirg
timfeirg

Reputation: 1512

python optional argument to optional argument validation

In python, how to validate optional-to-optional keyword arguments?

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.

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:

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

Upvotes: 4

Views: 530

Answers (1)

user2357112
user2357112

Reputation: 280335

There's no specific syntax for this at Python level. 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. Here's 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;

The use of PyArg_ParseTuple means that this function doesn't actually accept any arguments by name. If you do os.fdopen(sth, bufsize=16), you'll get a 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. 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.

Upvotes: 2

Related Questions