Re: Other Py_None like objects in python?

Guido.van.Rossum@cwi.nl
Wed, 08 Mar 1995 10:45:05 +0100

> I want to implement other Py_None like objects for some code I'm
> working on, and I was wondering if this is a frowned-upon practice.
> For instance, I am implementing a random bit module as part of my
> simulation code and something like a Py_True and Py_False would be
> nice instead of a Py_BuildValue everytime I return from my C code
> (this crates a new object and eats up memory, right?) Does anyone
> have a better suggetion for constant objects in Python?

It's not completely clear what aspect of Py_None you want to mimic
here, but it looks like you have a function that needs to return the
same integer value all the time. In fact if you use Py_BuildValue or
PyInt_FromLong to create a small integer, you *won't* (necessarily)
create a new object -- the latter maintains a cache containing the
integers -1 through 99 (or so) and will bump the refcnt and return an
existing object if it is in the cache (and the former just calls the
latter).

For more complicated objects that you need to return lots of times,
you can the same yourself: simply allocate the object once and store
it in a global varuable, and when you return it, just bump the refcnt.

I would advise against statically allocating an object (which is how
Py_None is implemented) since the initialization is dependent on the
object structure, which is intended to be opaque.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>