reference counting unlike programs written in pythonc extensions may have to manipulate the reference count of python objects this is done using the following macrosall of which are applied to objects of type pyobject macro description py_incref(objincrements the reference count of objwhich must be non-null py_decref(objdecrements the reference count of objwhich must be non-null py_xincref(objincrements the reference count of objwhich may be null py_xdecref(objdecrements the reference count of objwhich may be null manipulating the reference count of python objects in is delicate topicand readers are strongly advised to consult the "extending and embedding the python interpreterdocument available at as general ruleit is not necessary to worry about reference counting in extension functions except in the following casesn if you save reference to python object for later use or in structureyou must increase the reference count similarlyto dispose of an object that was previously saveddecrease its reference count if you are manipulating python containers (listsdictsand so onfrom cyou may have to manually manipulate reference counts of the individual items for examplehigh-level operations that get or set items in container typically increase the reference count you will know that you have reference counting problem if your extension code crashes the interpreter (you forgot to increase the reference countor the interpreter leaks memory as your extension functions are used (you forgot to decrease reference countthreads global interpreter lock is used to prevent more than one thread from executing in the interpreter at once if function written in an extension module executes for long timeit will block the execution of other threads until it completes this is because the lock is held whenever an extension function is invoked if the extension module is thread-safethe following macros can be used to release and reacquire the global interpreter lockpy_begin_allow_threads releases the global interpreter lock and allows other threads to run in the interpreter the extension must not invoke any functions in the python api while the lock is released py_end_allow_threads reacquires the global interpreter lock the extension will block until the lock can be acquired successfully in this case lib fl ff