Shadowing builtins (was Re: a pyrex-inspired for-i-from-1-to-n...)

Peter Hansen peter at engcorp.com
Wed Apr 2 16:27:14 EST 2003


Skip Montanaro wrote:
> 
>     >> range = my_custom_range_function
>     >>
>     >> would be OK. While,
>     >>
>     >> some_random_module.range = my_custom_range_function
>     >>
>     >> would not.
> 
>     Peter> Hmm.... that is exactly what is needed to make this effective in
>     Peter> unit testing.  One imports the module under test, then fakes the
>     Peter> open method in that other module:
>     ...
>     Peter> I'm not sure what other approach could be as simple, elegant, and
>     Peter> effective and I worry about losing it.  Surely there are many
>     Peter> other people doing similar things who would be hurt by this.
> 
> How about calling new.module() to create a new module object from the one
> you want to test which has suitably munged globals?

Interesting idea... but I'm a little unclear on what approach we would
be taking to get all the names/references from the old module into the
new one.  Pretend I'm really sleepy and having trouble following you here
(I don't have to pretend... it's the truth).  

import new
from mock_files import mockOpen
import module_under_test as mut

# create substitute module
mungedMut = new.module('dummy')

# populate with stuff from old module
for key,item in mut.___dict__.items():
    mungedMut.__dict__[key] = item

# install mock open again
mungedMut.open = mockOpen

What I don't understand is the difference between the final line above
and what I was originally trying to do, except that this is a newly
created module instead of one that was imported.

Okay, I guess I must have missed a key point and I'm way off the 
track here.  Please clarify.

-Peter




More information about the Python-list mailing list