Py_INCREF() incomprehension

Hegedüs Ervin airween at
Tue Apr 26 20:44:26 CEST 2011


> >But, when I don't read input arguments (there isn't
> >PyArg_ParseTuple), there isn't exception.
> >
> >How Python handle the number of arguments?
> From what you tell it: with PyArg_ParseTuple(). (see
> for this).
> You give a format string (in your case: "ss", again: better use
> "s#s#" if possible) which is parsed in order to get the (needed
> number of) parameters.
> If you call with () or only one arg, args points to an empty tuple,
> but the parser wants two arguments -> bang.
> If you call with more than two args, the function notices it too:
> the arguments would just be dropped, which is probably not what is
> wanted.
> If you call with two args, but of wrong type, they don't match to
> "s" (=string) -> bang again.
> Only with calling with the correct number AND type of args, the
> function says "ok".
> Why is "s#" better than "s"? Simple: the former gives the string
> length as well. "s" means a 0-terminated string, which might not be
> what you want, especially with binary data (what you have, I
> suppose).
> If you give e.g. "ab\0cd" where "s" is used, you get an exception as
> well, as this string cannot be parsed cmpletely. So better use "s#"
> and get the length as well.

so, if em I right, if PyArg_ParseTuple() fails, _it_ raises
TypeError exception... (?)

I think it's clear, thanks :)
> >I just ask this,
> >because I don't set errstring with PyErr_SetString, but I get
> >TypeError - how does Python knows, this error raised?
> There is magic inside... :-)

waov :)

and (maybe) final question: :)

I defined many exceptions:

static PyObject *cibcrypt_error_nokey;
static PyObject *cibcrypt_error_nofile;
static PyObject *cibcrypt_error_badpad;

void handle_err(int errcode) {
    switch(errcode) {
        case -1:    PyErr_SetString(cibcrypt_error_nokey, "Can't find key.");
    cibcrypt_error_nokey = PyErr_NewException("cibcrypt.error_nokey", NULL, NULL);
    PyModule_AddObject(o, "error", cibcrypt_error_nokey);

I am right, here also no need any Py_INCREF()/Py_DECREF() action,
based on this doc:

"Another useful function is PyErr_SetFromErrno(), which only
takes an exception argument and constructs the associated value
by inspection of the global variable errno. The most general
function is PyErr_SetObject(), which takes two object arguments,
the exception and its associated value. You don’t need to
Py_INCREF() the objects passed to any of these function"

so, this part of code is right?

thanks again:


More information about the Python-list mailing list