[TIP] Patching __import__

Michael Foord michael at voidspace.org.uk
Tue May 24 15:22:30 PDT 2011


On 24/05/2011 19:38, Kumar McMillan wrote:
> On Tue, May 24, 2011 at 1:16 PM, Michael Foord<michael at voidspace.org.uk>  wrote:
>> Right, but the point is that using patch.dict *isn't* an import hook. It
>> only adds (and then removes or restores) that entry from the sys.modules
>> dict when the decorated test is executed.
>>
>> *However*, it does get a reference to the sys.modules dictionary at import
>> time (to know which dictionary to patch) - and as the problem is happening
>> you're probably right about why. It's just that getting a reference to
>> sys.modules is not unusual in Python code, so I don't think it is "playing
>> with fire". It is a very odd interaction.
> Yeah, it definitely should be possible to munge sys.modules without
> ill effects.  If you can pinpoint it in Nose, please file a bug :)
> http://code.google.com/p/python-nose/
>
> I haven't fully thought it through but you might be able to implement
> this feature cleaner as an actual import hook.

Hmmm... actually I would see patch.dict as a *cleaner* solution (more 
lightweight, more localised, using a simple mechanism) but I realise 
that is an aesthetic judgement.

As an import hook there are other issues though. A PEP 302 importer is 
*not* called for importing a module that has already been imported, and 
overloading __import__ has all the drawbacks listed in PEP 302.

Not working with nose is a pretty big downside with the patch.dict 
approach though. I'm curious enough that I might actually look into it...

All the best,

Michael Foord

>> All the best,
>>
>> Michael Foord
>>
>>> You could try:
>>>
>>> nosetests --debug=nose.importer,nose.inspector,nose.selector
>>>
>>> to see if that gives you some clues before / after commenting out the
>>> @patch.dict line.  You could also try:
>>>
>>> nosetests --no-path-adjustment
>>>
>>> to turn off the import hooks.
>>>
>>>
>>>> Tried to debug it a bit but no luck...
>>>> Any ideas?
>>>> _______________________________________________
>>>> testing-in-python mailing list
>>>> testing-in-python at lists.idyll.org
>>>> http://lists.idyll.org/listinfo/testing-in-python
>>>>
>>>>
>>> _______________________________________________
>>> testing-in-python mailing list
>>> testing-in-python at lists.idyll.org
>>> http://lists.idyll.org/listinfo/testing-in-python
>>
>> --
>> http://www.voidspace.org.uk/
>>
>> May you do good and not evil
>> May you find forgiveness for yourself and forgive others
>> May you share freely, never taking more than you give.
>> -- the sqlite blessing http://www.sqlite.org/different.html
>>
>>


-- 
http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html




More information about the testing-in-python mailing list