Load objects using __import__

MindClass jonas.esp at googlemail.com
Tue Nov 21 15:25:45 CET 2006


Indeed before reading your message I solved it doing:

model_name = Country
mod = eval('i18n_module.%s' % model_name)
c1 = mod(name="Afghanistan")
exec c1

but I'll use getattr as you say. Thanks

Carl Banks ha escrito:

> MindClass wrote:
> > But when I load the object I get
> >     SyntaxError: invalid syntax
> >
> >     c1 = <module 'project.I18n.models' from
> > '/home/lala/django/project/I18n/models.pyc'>.Country(name="Afghanistan")
>
> It looks like you're running generated code somewhere, but passing the
> module itself rather than the name of the module to the code generator
> by mistake.  Perhaps you're execing some code that you pass the module
> name to?  Something like this?
>
> exec 'c1 = %s.Country(name="Afgahanstan")' % module_name
>
> You seem to be erroneously using the module itself, not the module
> name.
>
> That's about all I can help without more information.
>
>
> P.S. if you are doing that, consider using getattr instead of exec.
> 
> c1 = getattr(module,Country)(name="Afgansitan")
> 
> 
> Carl Banks




More information about the Python-list mailing list