Filling the namespace inside the module before loading it

I developed a configuration mechanism in Python, where certain objects can work in special ways to identify problems in our domain.

The user poses a problem using these objects in the form of a "config-file". For instance:

# run configuration
CASES = [
 ('Case 1', Item('item1') + Item('item2') + Item('item3')),
 ('Case 2', Item('item1') + Item('item4')),
]

DATA = {
 'Case 1' = {'Piece 1': 'path 1'},
 'Case 2' = {'Piece 1': 'path 2'},
}

Objects Item, of course, are defined in a specific module. To use them, you must issue an instruction import: from models import Item(of course, my actual import is more complex, not just one).

I would like the user to simply write the presented configuration without the need for import (users can very easily forget this).

, , .

?

Edit:

Django, "" python script, -. , Python " ( Item - ), script - , ".

+3
2

eval:

>>> help(eval)
Help on built-in function eval in module __builtin__:

eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

eval.

with open(source) as f:
    eval(f.read, globals(), {'Item': Item}) 

, Python? , . ConfigParser, , , Windows.

[cases]
case 1: item1 + item2 + item3
case 2: item1 + item4

[data]
case 1: piece1 - path1
case 2: piece1 - path2
+1

1) , , ; ?

script, :

$ python application_run.py --generate_settings 

, , :

import sys
from models import Item

# Complete the information here please !!!
CASES = []
DATA = {}

2) - execfile(), script, settings.py

root_settings.py

# All import defined Here.
from Model import Item
...

execfile('settings.py')

, , root_settings, , , settings.py, root_settings.py.

0

Source: https://habr.com/ru/post/1781922/


All Articles