Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass function definition to python script as string

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?
  4. execute
  5. cleanup

But I am sure there must be a better way.

like image 346
Jan Grz Avatar asked Feb 16 '26 01:02

Jan Grz


1 Answers

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)
like image 114
asadmshah Avatar answered Feb 18 '26 15:02

asadmshah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!