Programmatically replacing an API for another module

Gabriel Genellina gagsl-py at
Tue Nov 21 02:10:09 CET 2006

At Monday 20/11/2006 21:52, Tom Plunket wrote:

>What I ran into after posting is that I don't know how to get the
>__dict__ for the module's scope; is it available?  I.e. I can do
>'print os.path.__dict__', but 'print __dict__' at module scope results
>in a NameError since __dict__ is undefined at that scope.  However, if
>I could do 'os.path = local_module' somehow, I'd be getting basically
>what I want.  Maybe I could just have a, and in my test
>code import it as os.path, and then the other code would see that
>os.path is already loaded and not bother doing so again?  Haven't
>tried it, am interested in the answer, but I do have enough to work
>with for now...  Replacing a module in this way also ensures that I'm
>only calling the parts of the API that I intend to call, which is a
>handy side-effect.

You can do this:
import my_os_path
os.path = my_os_path

That shows also that you can use the module as its own namespace. No 
need to use __dict__ explicitely. dir(module) gives you the names 
defined in the module. From inside the module self, use globals().

Gabriel Genellina
Softlab SRL 

Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! -

More information about the Python-list mailing list