[Patches] [ python-Patches-730473 ] Add Py_AtInit() startup hook for extenders

SourceForge.net noreply@sourceforge.net
Wed, 30 Apr 2003 15:26:34 -0700


Patches item #730473, was opened at 2003-04-30 15:26
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=305470&aid=730473&group_id=5470

Category: Core (C code)
Group: Python 2.3
Status: Open
Resolution: None
Priority: 5
Submitted By: Patrick Miller (patmiller)
Assigned to: Nobody/Anonymous (nobody)
Summary: Add Py_AtInit() startup hook for extenders

Initial Comment:
I work on several projects that have initialization
requirements that
need to grab control after Py_Initialize(), but before
any user code
runs (via input, script, -c, etc...).

Note that these are Python clones that take advantage
of an installed
python (using its $prefix/lib/pythonx.x/*.py and
site-packages/*)

We could use 

PyImport_AppendInittab("sitecustomize",initsitecustomize);

But if there already IS customization in
sitecustomize.py, I've
blown it away (and have to look it up and force an
import).
And if someone uses the -S flag, I'm screwed.

I propose a hook styled after Py_AtExit(func) called
Py_AtInit(func)
which maintains a list of functions that are called in
Py_Initialize
right after main and site initializations.

If the hook isn't used, then the cost is a single extra
function
call at initialization.  Here's a spurious example:  A
customer wants
a version of python that has all the math functions and
his
extensions to act like builtins...

I would write (without refcnt or error checks ;-):

#include "Python.h"
static void after_init(void) {
    PyObject
*builtin,*builtin_dict,*math,*math_dict,*user,*user_dict;

    builtin = PyImport_ImportModule("__builtin__");
    builtin_dict = PyModule_GetDict(builtin);
    math = PyImport_ImportModule("math");
    math_dict = PyModule_GetDict(math);
    user = PyImport_ImportModule("user");
    user_dict = PyModule_GetDict(math);

    PyDict_Update(builtin_dictionary, math_dict);
    PyDict_Update(builtin_dictionary, user_dict);
}


int main(int argc, char** argv) {
    PyImport_AppendInittab("user",inituser);
    Py_AtInit(after_init);

    return Py_Main(argc, argv);
}

voila!  An extended Python with new builtins.
This is vastly better than hacking in through
site.py or sitecustomize

I actually want this to do some MPI initialization to
setup a
single user prompt with broadcast which has to run
after
Py_Initialize() but before the import of readline.





----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=305470&aid=730473&group_id=5470