I wish to create a custom calculator where the user defines two parameters and a function using a GUI and when they click on calculate it executes their user defined function passing the two parameters.
argument1 = IntSlider( … )
argument2 = IntSlider( … )
userDefinedFunction = TextArea( … )
calculateButton = Button ( … )
calculateButton.on_click(userDefinedFunction)
So that let’s say somebody defines :
argument1 = 3
argument2 = 4
userDefinedFunction = def udf(arg1,arg2): return arg1**2 + arg2**2
Would return 25 as 3*3 + 4*4 = 25
.
I'd probably go with something more limiting than a full function definition. Having the user create the function signature is going to add complications as you cannot
eval
it, you would have toexec
it instead. Then finding out the method name would be complex, and it would allow the user to overwrite local variables, or do other imports, which might not be desirable.An easier way could be to expect the user to complete the lambda method
lambda arg1, arg2: <user code input>
.Note that
eval
andexec
(or running any unvalidated user input as code for that matter) are dangerous. If the user is running this on their local machine only this is somewhat okay, but do not do this if the inputs are coming from external sources, like for example, a web server.