0

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:

  1. do you think it's a good way to go?
  2. can I always pass a dictionary as proposed by the author to any function?
  3. 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?
Community
  • 1
  • 1
Ottavio Campana
  • 4,088
  • 5
  • 31
  • 58

1 Answers1

5

You can just do:

function_to_be_called(**option_dict)

The old way to do this was with the apply function, but that has now been deprecated for the *args, and **keywords syntax.

This is actually really cool, since it means you can have a function and a tuple of arguments and call the function, so:

def polly(cracker, wants):
    if wants:
       print 'polly wants a', cracker
f = polly
t = ('cracker', True)

These are now all equivalent:

polly('cracker', True)
polly(*('cracker', True))
polly(*t)
f('cracker', True)
f(*t)

Now expand that for keyword arguments - but look up a real tutorial. But as @Duncan points out, you can do this:

polly(**{cracker: 'cracker', wants: True})
d = {cracker: 'biscuit', wants: True}
polly(**d)
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • 2
    and more importantly for answering the actual question `d = { 'cracker': 'nut', 'wants': False}` `polly(**d)` is also equivalent. – Duncan Feb 09 '12 at 09:38