Something like ast.literal_eval to execute variable assignments
<p>I want to do something like:</p>

<pre><code>import ast

def foo(common_stuff, assignment_str):
    common_stuff()
    ast.literal_eval(assignment_str) # assignment to unknown or passed variable

foo('a=1;b=2')
</code></pre>

<p>is this possible in Python?</p>

<p>I am trying to write a general function to (enforce DRY) for this:</p>

<pre><code>    for f, i in zip(task_set, xrange(len(task_set))):
        cd = f.cleaned_data
        t_name = cd.get('t_name')
        start_date = cd.get('start_date')
        end_date = cd.get('end_date')
        project = Project.objects.get(pro_id=p.pro_id)
        task = Task(t_name=t_name, start_date=start_date,
                    end_date=end_date, project=project)
        task.save()
        tasks_list.append(task)
</code></pre>

<p>So I started writing the following:</p>

<pre><code>def save_form(model, formset, foreignkey_assignment, *args){
    for f, i in zip(formset, xrange(len(formset))):
        cd = f.cleaned_data
        get_key_name = lambda x: cd.get(x)
        ast.literal_eval(foreignkey_assignment)
        m = model(**{k:get_key_name(k) for k in args})
        m.save()
}
</code></pre>

<p>Yes you can</p>

<pre><code>exec('a=1;b=2')
</code></pre>

<p>but you shouldn't.
<a href="http://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided">Why should exec() and eval() be avoided?</a></p>

python eval variable-assignment literals