0

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 Answer 1

4

“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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.