[Python-Dev] Hook Extension Module Import?

Aahz aahz@pythoncraft.com
Sun, 20 Apr 2003 14:31:05 -0400


On Sun, Apr 20, 2003, David Abrahams wrote:
> Aahz <aahz@pythoncraft.com> writes:
>> On Sun, Apr 20, 2003, David Abrahams wrote:
>>> Aahz <aahz@pythoncraft.com> writes:
>>>> On Sun, Apr 20, 2003, David Abrahams wrote:
>>>>> 
>>>>> I think I need a way to temporarily (from 'C'), arrange to be notified
>>>>> just before and just after a new extension module is loaded.  Is this
>>>>> possible?  I didn't see anything obvious in the source.  BTW, I'd be
>>>>> just as happy if it were possible to do the same thing for any module
>>>>> (i.e., not discriminating between extension and pure python modules).
>>>>
>>>> http://www.python.org/peps/pep-0302.html
>>> 
>>> I guess I should take that to mean "you can't do that yet" (?)
>>
>> As the PEP says, you *could* define an __import__ hook, but that would
>> likely be more effort than you want.
> 
> It also says:
>    
>     The situation gets worse when you need to extend the import
>     mechanism from C: it's currently impossible, apart from hacking
>     Python's import.c or reimplementing much of import.c from scratch.
> 
> OTOH, it's not obvious to me why this should be so.  Can't I
> access/replace builtins.__import__ from C/C++?

Sure, but then you need to replace import.c, just as it says.  I'd be
inclined to do the heavy lifting in Python with a callback into C code
(after all, you're not calling it so frequently as to make it a
performance issue).
-- 
Aahz (aahz@pythoncraft.com)           <*>         http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?