Dynamic and lazy import

Stargaming stargaming at gmail.com
Wed Oct 17 01:26:34 EDT 2007


On Tue, 16 Oct 2007 13:16:50 +0000, Alexandre Badez wrote:

> Hye everyone,
> 
> I'm would like to do something a bit tricky.
> 
> 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...).
> 
> Any idea ?
> Is it possible ?

Depending on the exact complexity of your needs and exact use case just 
inserting some code on top of every module could suffice. To reduce 
boilerplate, if the task you're trying to realize is pretty generic for 
every module, you could insert another module hiding this code and used 
like this::

    from .modregister import init
    init(__name__)

If you really have to _create_ modules dynamically, follow the advice 
given earlier in this thread.

HTH,
Stargaming



More information about the Python-list mailing list