Question on dynamically loaded modules.

Alex Martelli aleax at aleax.it
Mon Mar 24 06:17:46 EST 2003


Adonis wrote:

> What is the best way to instantiate a module's class and it's members

This question is quite unclear -- "a module's class" seems to state
that a module has only one class, and I'm not sure what "it's members"
refers to.

> given that the module(s) can be loaded at any given time?
> 
> i.e. (pseudo code)
> 
> for module in module_list:

module_list needs to be a list of strings (module names).

>     import module

this needs to be something like:

    modobj == __import__(module)

>     ...then how to obtain its classes and initialize them
> 
> I understand I need to use the dir() function (or a better way?), but what
> would be the most effective avenue to do this?

Obtaining the class objects exposed at top-level by the module is easy,
e.g.:

    import types
    clss = [v for v in vars(modobj).values() if type(v) is types.ClassType]

this will not get newstyle classes, though -- only classic classes.  If
you also want newstyle classes *and types* (no way to distinguish), then
you may try using something like:

    from types import ClassType as CT
    clss = [ v for v in vars(modobj).values() if type(v) in (CT,type) ]

this STILL fails to get classes with custom metaclasses, but let's stop
here for now and assume for the moment that you don't care about those.

Now to "initialize" (not sure what you mean by that) or "instantiate"
(create an instance of) each class you may need to call it *with appropriate
arguments* -- and there is no way to tell which the appopriate arguments
might be.  With substantial effort you may find out how MANY arguments
a class wants to be called with for instantiation, and the names of those
arguments, but you have no way to divine the MEANING of those arguments
in general, and thus to supply the right values for them.


So, you may indeed need to clarify your problem better -- why do you
want to find out all classes supplied by the module, what exactly do
you want to do with each one that you find, and, perhaps, WHY...


Alex





More information about the Python-list mailing list