HOWTO: Deal with reference counts in Grid classes

The C++ grid wxGridCellEditor, wxGridCellRenderer and wxGridCellAttr classes use an internal ref-counting scheme that is unfortunately a bit different from how Python’s ref-counting works, so it is easy to get confused as to when you need to call IncRef or DecRef on these objects. Unfortunately we currently need to manage the life of those objects like is done in C++, instead of relying on Python common-sense to do it for us.

Here are some tips that may help:

  • You can use GetRefCount to track what the internal count is, and perhaps give you some ideas about the source of the extra or deficit counts, or at least ideas of what you can try to maybe solve it.

  • The refcount starts at 1 when you create a new object. If you are just going to assign it to a cell or an attribute or whatever and then throw away your local reference, then you don’t need to do anything. The thing you assigned it to will take over that reference count of 1 and manage it properly from then on.

  • If you want to hold on to the object in order to use it again later with other cells or whatever, then you must call its IncRef method. And, IIRC, you’ll need to call it again each time you reuse it.

  • If you are holding on to an object and incref-ing it each time you reuse it, then you should be sure to call DecRef when you are done with it, and before the grid is destroyed. This is especially true with GridCellEditors since they have one or more widgets that need to be properly disconnected from the grid before they are destroyed. If you get an exception about an wxEvtHandler not being popped then this is probably the problem.

  • When you use a getter to fetch a refcounted item from the grid or from an attr then it may have been increfed before being given to you. When you are done with it you may need to call DecRef. Use GetRefCount to double-check.