Loading functions from a file during run-time

Nick Coghlan ncoghlan at iinet.net.au
Fri Feb 11 08:33:52 EST 2005


Bryant Huang wrote:
> Hello!
> 
> I would like to read in files, during run-time, which contain plain
> Python function definitions, and then call those functions by their
> string name. In other words, I'd like to read in arbitrary files with
> function definitions, using a typical 'open()' call, but then have
> those functions available for use.
> 
> The 'import' keyword is not appropriate, AFAIK, because I want to be
> able to open any file, not one that I know ahead of time (and thus can
> import at design-time).

This usage is one of the reasons why the __import__ function exists (despite 
what its docs say). It's right there at the top of the library reference's 
'builtin functions' section:

http://www.python.org/dev/doc/devel/lib/built-in-funcs.html

Instead of writing "import foo as mod" you can write "mod = __import__('foo')". 
The first is better when you do know the name of the module you want at coding 
time, but the latter is handy when you want to be dynamic about it.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list