Differences between revisions 1 and 2
Revision 1 as of 2005-04-14 22:54:05
Size: 1070
Editor: 168-103-146-113
Comment: How dynamically find modules in a directory, import them, get a handle to them?
Revision 2 as of 2005-04-14 23:11:51
Size: 1213
Editor: 168-103-146-113
Comment:
Deletions are marked like this. Additions are marked like this.
Line 45: Line 45:

There seems to be [http://www.python.org/doc/current/lib/module-imp.html a module imp] that can be used to dynamically load a named module.

I frequently want to find all the modules in some directory, with some property, and do something with them.

If you know how, please inform me. Here are some things I'm researching.

Finding the Things Inside a Module

   1 module.__dict__

Identifying Functions

   1 import types
   2 
   3 def is_it_a_function(obj):
   4     return isinstance(obj, types.FunctionType)

Finding Functions Within a Module

So, putting them together,...

   1 def functions_in_module(module)
   2     functions = []
   3     for obj in module.__dict__.values():
   4         if isinstance(obj, types.FunctionType):
   5             functions.append(obj)
   6     return functions

Finding Modules in a Directory

Is there a better way than just listing the contents of the directory, and taking those tiles that end with ".pyc" or ".py"..?

Importing the Modules

How do you do it dynamically, just given a filename?

Once you've imported it, how do you get a handle on it? (That is, how do you get it's dict?)

There seems to be [http://www.python.org/doc/current/lib/module-imp.html a module imp] that can be used to dynamically load a named module.

ModulesAsPlugins (last edited 2010-06-14 22:06:18 by c-98-207-20-119)

Unable to edit the page? See the FrontPage for instructions.