I was reading some questions about not to use exec or eval in python code.
I currently have a python web program based on pyramid and it takes some variables from a form and calls a function. All the argument of this function or optional, thus more or less what I do is
command = 'function_to_be_called ('
if optional_variable_in_form in request.params :
command += 'optional_variable=optional_variable_in_form'
command += ')'
i = eval (command)
I am trying to enhance my application and I am trying to replace eval with something else. I found this answer, where the author suggests to pass a dictionary by reference instead of using my solution.
So my questions are:
- do you think it’s a good way to go?
- can I always pass a dictionary as proposed by the author to any function?
- I find quite ofter the **, but I don’t understand well what it does. Can you give me a hint about it or suggest a good page where I can study about it?
You can just do:
The old way to do this was with the
applyfunction, but that has now been deprecated for the*args, and**keywordssyntax.This is actually really cool, since it means you can have a function and a tuple of arguments and call the function, so:
These are now all equivalent:
Now expand that for keyword arguments – but look up a real tutorial. But as @Duncan points out, you can do this: