Py_INCREF() incomprehension

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Sun May 1 20:59:55 EDT 2011


Am 01.05.2011 22:00, schrieb Hegedüs Ervin:

> My module contains just 4 functions (in C), which translate 3rd
> party lib to Python. The name would be _mycrypt.so example.
>
> I wrapped it a pure Python module, its name is mycrypt.py.
>
> Then, I've import pure Python module in a main program, like
> this:
>
> =%=
> mycrypt.py:
>
> import _mycrypt
> ...
> =%=
>
> =%=
> userapp.py:
>
> import mycrypt
> ...
> =%=

AFAICS, it looks ok.


> I've missed out something, and then I didn't get exception,
> instead there were a segfault. :(

I guess this is the point where yo should start printf programing.

* What happens during module initialization?
* What happens n the functions?
* Where does the stuff fail?
* What are the reference counts of the involved objects?

etc.


> I've put it a Py_INCREF() after every PyModule_AddObject(), eg.:
>
>      PyModule_AddObject(o, "error", cibcrypt_error_nokey);
>      Py_INCREF(cibcrypt_error_nokey);
>
> and now if there is some expected exception, I get it.

> Any explanation?

I don't have one - I would think that if the module object exists for 
all the time, it would be enough to have one reference there.

But obviously it is not enough - did you at any time del something 
related to here? The module or one of its attributes?

Anyway, it seems safer to do INCREF here - so do it. (As Gregory already 
stated - it looks cleaner if you do INCREF before AddObject.)


> ps: this is just for my passion, but I would like to understand
> it very-very much :)

Understandable. That's that the printf debugging of the refcounts can be 
good for - even if you don't really have a problem.


Thomas



More information about the Python-list mailing list