Load objects using __import__

MindClass jonas.esp at googlemail.com
Tue Nov 21 08:14:46 EST 2006


I load objects from a file (to django framework _but it's a python
question_).

1) Before I used this
    from project.I18n.models import *

And to load the object
    c1 = Country(name="Afghanistan")

But the problem is that there is to edit 'project' manually.

2) So I setup the environment and import the module:
    project_directory = os.path.abspath('')
    project_name = os.path.basename(project_directory)
    os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % project_name
    sys.path.append(os.path.dirname(project_directory))
    module = __import__('%s.I18n.models' % (project_name), {}, {},
[''])
    sys.path.pop()

It's all correct until here and to checking it I run:
    print i18n_module
    <module 'project.I18n.models' from
'/home/lala/django/project/I18n/models.pyc'>

    print i18n_module.Country
    <class 'project.I18n.models.Country'>

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")

Any idea?




More information about the Python-list mailing list