import class from string
t at jollybox.de
Thu Jul 5 00:55:05 CEST 2012
On 07/04/2012 10:27 PM, Mariano DAngelo wrote:
> Hi I'm trying to create a class from a string....
> This is my code, but is not working....
It would be helpful if you posted an error message. Then, we could know
what's actually going on.
> module_name, class_name = model.rsplit(".", 1)
> module = importlib.import_module(module_name)
> class_ = getattr(module, class_name)()
These brackets may be causing problems?
In principle, you're doing the right thing. This works for me:
Python 3.2.3 (default, May 3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> objname = 'os.path.join'
>>> module_name, member_name = objname.rsplit('.', 1)
>>> module = importlib.import_module(module_name)
>>> member = getattr(module, member_name)
<function join at 0x7f882f4b0af0>
More information about the Python-list