Coder Social home page Coder Social logo

paulross / pythonextensionpatterns Goto Github PK

View Code? Open in Web Editor NEW
214.0 14.0 32.0 5.39 MB

Examples of safe coding practice for Python C extensions.

License: MIT License

Python 8.66% Shell 0.11% C 87.14% Roff 4.08%
python python-extension c python-c-api

pythonextensionpatterns's People

Contributors

adamormondroyd avatar gdevanla avatar miurahr avatar paulross avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pythonextensionpatterns's Issues

Gotos Don’t Nest

Based on the issues I have raised already, I think your whole goto-based approach is flawed. The right way is to adopt an overall structured-programming pattern that looks like this:

«pointer» = NULL;
do /*once*/
  {
    ... possible preceding code ...
    allocate «pointer»;
    if («error_occurred»)
        break;
    ... do something with «pointer» ...
  }
while (false);
Py_XDECREF(«pointer»);

This kind of structure nests easily and scales to more complex cases, which is vital for dealing with allocation inside loops, for example. (I notice you don’t discuss these.) Avoiding gotos helps guarantee that control paths from inner structures cannot avoid going through the cleanup on their way out.

I have a couple of more concrete examples to offer, in the form of Python modules I wrote for my grainypy and dvd_menu_animator projects, which demonstrate this idea in action.

COUNT_ALLOCS was removed in Python3.9

I spent a bit of time following the (normally excellent) advice in this tutorial to try a COUNT_ALLOCS build while debugging a reference leak and found that it did nothing. It turns out CPython removed the functionality in Python 3.9. See python/cpython#18259.

Unfortunately there isn't a replacement.

Should all the text referencing COUNT_ALLOCS just be removed? It would avoid wasting the time of future people who would like to debug reference issues.

I ended up fixing the issue I had by setting a breakpoint on the variable in the debug python build tracking the total number of allocations and then over the course of a python for loop that leaked memory every loop, simply printed out the objects getting increfd and decrefd and found the place where an object was getting an extra incref. Maybe I could describe this debugging process?

Flaw With Static Default Args?

Looking at your _parse_args_with_python_defaults routine defined here, your pyObjDefaultArg_0 and pyObjDefaultArg_1 remain partially allocated even if an exception occurred after they were allocated, but before they were completely initialized. What if the user trapped that exception, let their script continue execution, and then tried calling into your code again? This time it would assume the default objects were fine, and you could end up returning a partially-initialized object. You need to completely free up partially-allocated objects on an exception.

Some Memory Leaks

I see a couple of concerns in your section on Getting and Setting Module Globals.

In a statement like

if (PyModule_AddObject(m, NAME_TUP, Py_BuildValue("iii", 66, 68, 73))) {
    goto except;

the doc says that the reference to the object is only stolen on success. So if the PyModule_AddObject call fails, then the object created by the Py_BuildValue call in this case will be leaked.

Further down that page, the calls to PyDict_SetItem (e.g. PyDict_SetItem(pMap, PyBytes_FromString("123"), PyLong_FromLong(123))) leak references to the key and value objects.

valgrind still reports tons of possible leaks

  1. a typo: Uncomment PyObject_Free and PyObject_Realloc in the valgring suppression file.
    valgring should be valgrind
  2. I installed debug version of python3 as detailed in the doc, when I use it with valgrind(just open python and exit), it still reports tons of possible leaks, is that possible to suppress them?

this is a really nice book/tutorial

this is a really nice book/tutorial, I read it a few months ago, when I tried to search and read it again today, it is really hard to find it, I think it would be better to have keyword like C extension in the title. Anyway, just some random thoughts. Thank you for the writing.

A trivial typo (so patch instead of pull request)

From e47c876f1aecf475b43a942521ed9b3ce9be3dc6 Mon Sep 17 00:00:00 2001
From: Cong Ma <[email protected]>
Date: Fri, 4 Nov 2016 13:31:21 +0800
Subject: [PATCH] Fix typo (Py_DECREF) in canonical_function.rst.

---
 doc/sphinx/source/canonical_function.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/doc/sphinx/source/canonical_function.rst b/doc/sphinx/source/canonical_function.rst
index c7762b3..0ea064a 100644
--- a/doc/sphinx/source/canonical_function.rst
+++ b/doc/sphinx/source/canonical_function.rst
@@ -71,7 +71,7 @@ If you are willing to accept NULL arguments then this pattern would be more suit
         Py_INCREF(arg_1);
     }
     
-Of course the same test must be used when calling ``Py_DECFREF``, or just use ``Py_XDECREF``.
+Of course the same test must be used when calling ``Py_DECREF``, or just use ``Py_XDECREF``.
 
 Now we create any local objects, if they are "Borrowed" references we need to incref them. With any abnormal behaviour we do a local jump straight to the cleanup code.
 
-- 
2.10.2

possible tipo

Introduction: pLast is probably pObj here:

PyObject_Print(pLast, stdout, 0);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.