Loading a class the name of which is only known runtime

Simon Burton simonb at webone.com.au
Tue Apr 8 13:35:19 EDT 2003


On Tue, 08 Apr 2003 18:31:23 +0200, Mads Orbesen Troest wrote:

> Hi folks;
> 
> "And now for something completely different:"
> 
> I have a situation in which I, from a CGI script written in Python, want to 
> instantiate a class, the name of which is known to me only at runtime 
> (because it depends on a CGI parameter).
> 
> Is it possible to load (import and instantiate) a class dynamically in 
> Python? I have a feeling the answer is Yes, but as I am unfortunately not 
> quite the python expert (yet :) forgive me if I ask something obvious.
> 
> Thanks in advance,
>    /\/\\ads Orbesen Troest

[simon at arrow simon]$ python
Python 2.2.2 (#2, Nov 24 2002, 11:41:06) 
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Make it so.
>>> class foo:
...   pass
... 
>>> 
>>> name = "foo"
>>> 
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 'foo': <class __main__.foo at 0x81c302c>,
 'inspect': <module 'inspect' from '/usr/lib/python2.2/inspect.pyc'>,
 'my_print': <function my_print at 0x81c1f44>,
 'name': 'foo',
 'pprint': <module 'pprint' from '/usr/lib/python2.2/pprint.pyc'>,
 'readline': <module 'readline' from '/usr/lib/python2.2/lib-dynload/readline.so'>,
 'rlcompleter': <module 'rlcompleter' from '/usr/lib/python2.2/rlcompleter.pyc'>,
 'string': <module 'string' from '/usr/lib/python2.2/string.pyc'>,
 'sys': <module 'sys' (built-in)>,
 'types': <module 'types' from '/usr/lib/python2.2/types.pyc'>}
>>> locals()[name]
<class __main__.foo at 0x81c302c>
  __doc__=None
  __module__='__main__'
>>> instance = locals()[name]()
>>> instance
<__main__.foo instance at 0x81c4c64>
  __doc__=None
  __module__='__main__'
>>> 





More information about the Python-list mailing list