How do I pass function definition to python script as string
Question: I want to pass **function definition** to a python command line script. What
is the best way to do this? I am using python 2. Suppose i have a script like
this:

    
    
    #myscript.py
    x = load_some_data()
    my_function = load_function_definition_from_command_line()
    print my_function(x)
    

And i want to call it like this: `python myscript.py 'def fun(x): return
len(x)'`

How do i perform the `load_function_definition_from_command_line` part ?

I imagine a workaround:

  1. get the string function definition from command line 
  2. write it to a file with .py extension in some temp directory
  3. load the definition from file using solutions from this question: [How to import a module given the full path?](http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path)
  4. execute 
  5. cleanup

But I am sure there must be a better way.


Answer: You can use `eval` to run code defined in a string. Like so:

    
    
    import sys
    
    x = load_some_data()
    function = eval("".join(sys.argv[1:]))
    print(function(x))
    

With your specific example though you might have to use something like `lambda
x: len(x)`

As @Jan-Spurny rightly points out: "Never, never, never use eval unless you're
absolutely sure there is no other way. And even then you should stop and think
again."

In my mind the better strategy would be to turn the data loader and executor
into a module with a method that takes a function as an argument and runs the
desired code. The end result something like this:

    
    
    import data_loader_and_executor
    
    def function(x):
        return len(x)
    
    data_loader_and_executor.run(function)
    

