Dynamic and lazy import

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Oct 17 05:53:48 CEST 2007

En Tue, 16 Oct 2007 10:16:50 -0300, Alexandre Badez  
<alexandre.badez at gmail.com> escribió:

> I would like when I do something like to create a __init__ package's
> (here calle my_package) file witch make an action when we try to
> import something in this package...
> Quiet like __getattribute__ work for a class, I would like this kind
> of behaviour for a whole module or a package
> be a bit clearer:
> I've got a normal package/module/class (whathever) where I do
> something like:
> from my_package import my_module
> (but in the my_package I've got only:
> my_package / __init__.py
> And in the __init__ of my my_package something like __getattribute__
> (but for a module) that would return something for my_module
> I know, that I can do something like charging everything "before" in
> __init__ like:
> my_module = the_thing_I_want
> But I need it to be lazy (because I may have many module witch could
> be very awful...).

A module doesn't *have* to be a module... You can replace  
sys.modules['your_module_name'] with a suitable object. See this classical  
recipe from Alex Martelli:

Gabriel Genellina

More information about the Python-list mailing list