julivico julivico - 6 months ago 11
Python Question

Import dict without name from a module

An Odoo module always has the two files

__init__.py
and
__openerp__.py
.

dhl_module
|-- controller
|-- models
|-- views
|-- __init__.py
|-- __openerp__.py


The file
__openerp__.py
contains a dict without assigning it to a name. This dict stores information about the module. It looks like this:

# -*- coding: utf-8 -*-
{
'name': "DHL connector",
# used as subtitle
'summary': "Configuration for DHL connector ",
'description': """ DHL connector
""",
'author': "me",
'website': "mysite.com",
'category': 'Technical Settings',
# Change the version every release for apps.
'version': '0.0.1',
# any module necessary for this one to work correctly
'depends': [],
# always loaded
'data': ['views/dhl.xml', ],
# only loaded in demonstration mode
'demo': [],
# only loaded in test
'test': [],
'installable': True,
'application': True,
}


How can Odoo or I access this dict from the
__openerp__.py
module? The dict variable is not assigned to a name. How can it be imported?

Answer

OpenERP doesn't have to import that module to get that dictionary. They could just read the file as text and just evaluate the contents with eval():

>>> text = '''\
... # -*- coding: utf-8 -*-
... {
...     'name': "DHL connector",
...     # used as subtitle
...     'summary': "Configuration for DHL connector ",
...     'description': """ DHL connector
...     """,
...     'author': "me",
...     'website': "mysite.com",
...     'category': 'Technical Settings',
...     # Change the version every release for apps.
...     'version': '0.0.1',
...     # any module necessary for this one to work correctly
...     'depends': [],
...     # always loaded
...     'data': ['views/dhl.xml', ],
...     # only loaded in demonstration mode
...     'demo': [],
...     # only loaded in test
...     'test': [],
...     'installable': True,
...     'application': True,
... }
... '''
>>> eval(text)
{'website': 'mysite.com', 'description': ' DHL connector\n    ', 'demo': [], 'depends': [], 'data': ['views/dhl.xml'], 'category': 'Technical Settings', 'name': 'DHL connector', 'author': 'me', 'summary': 'Configuration for DHL connector ', 'application': True, 'version': '0.0.1', 'test': [], 'installable': True}

And that is exactly what OpenERP does:

MANIFEST = '__openerp__.py'

# ...

terp_file = mod_path and opj(mod_path, MANIFEST) or False

# ...

f = tools.file_open(terp_file)
try:
    info.update(eval(f.read()))
finally:
    f.close()
Comments