tags:

views:

503

answers:

1

Hi there! My eval syntax isn't right. Namely, for each category, I'd like to output a ModelChoiceField named category_task, ie. if category were 'fun', then a radio select field 'fun_tasks' would be output.

categories = Category.objects.all()

for category in categories:
    eval(category)_tasks = form.ModelChoiceField(
        queryset         = Task.objects.filter(method__category=category),
        widget           = RadioSelect
    )
+1  A: 

“eval is evil.”

OK, it has its uses, but 90% of eval usage (in any language) is misconceived, so if you find yourself writing an eval you should stop and examine what you're doing with extreme suspicion.

eval(category)_tasks = x

If you are doing an assignment, that's a statement rather than an expression, so you'd have to use exec rather than eval:

exec category+'_tasks= x'

However exec is just as evil as eval!

You can write a variable in Python without having to parse/evaluate Python code:

locals()[category+'_tasks']= x

or, if you want to write a global variable instead of one in the current scope, replace locals() with globals().

Although this is better than eval/exec, it is still rather code-smelly. You rarely actually want completely dynamically-named variables; a lookup is usually much cleaner:

catlookup= {}
catlookup[category]= x

although without more context it's difficult to say what's best for your case.

bobince