Dynamical loading of modules

Jp Calderone exarkun at divmod.com
Mon Oct 3 15:56:56 EDT 2005



On Mon, 03 Oct 2005 21:52:21 +0200, Jacob Kroon <jacob.kroon at gmail.com> wrote:
>Hi, I'm having some problems with implementing dynamical module loading.
>First let me
>describe the scenario with an example:
>
>modules/
>    fruit/
>        __init__.py
>        apple.py
>        banana.py
>
>apple.py defines a class 'Apple', banana defines a class 'Banana'. The
>problem lies in the
>fact that I want to be able to just drop a new .py-file, for instance
>peach.py, and not change
>__init__.py, and it should automatically pickup the new file in
>__init__.py. I've come halfway
>by using some imp module magic in __init__.py, but the problem I have is
>that the instantiated
>objects class-names becomes fruit.apple.Apple/fruit.banana.Banana, whild
>I want it to be
>fruit.Apple/fruit.Banana.
>
>Is there a smarter way of accomplishing what I am trying to do ?
>If someone could give me a small example of how to achieve this I would
>be very grateful.

The __module__ attribute of class objects is mutable.  I don't understand *why* this makes a difference, though.  The class's name is a pointer to where it is defined: this is useful because it saves a lot of grepping, and unambiguously tells the reader where the class came from.  If you start making it mean something else, you'll end up confusing people.  If you just want a pretty name, use something /other/ than the class's fully qualified Python name.

Jp



More information about the Python-list mailing list