[Tutor] What Eval() Hath Men Wrought

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Jun 24 12:17:11 EDT 2004

> The C way to do it is to pass in a pointer to a function.

And you can pass a function object in Python too but...

> This is good because C nicely checks that the function
> 1) is actually a function
> 2) takes the right arguments
> 3) returns the right type.

Python does none of these, although you can explicitly
check the object is callable in the receiving code.

> The Matlab way to do it is to pass a string that contains
> the function name, and to use the Matlab feval function,
> .... but instead can use the form feval('function_name',argument).

You can use the Python apply() function to do a similar thing,
it takes a callable object and a tuple of arguments to be passed
to the callable.

> you get weird errors if the function name is wrong, or if
> the function takes an unexpected kind of argument or returns
> an unexpected type.

Yes, thats always a problem with this type of eval() behaviour.

> What is the right way to do this in Python?

There is no right way, mostly I would pass a function reference
as my preferred route and apply() as a close second if, for
example the functions took different numbers of arguments.

Note that you can get the callable function object from its
name by using the local namespace dictionary.

Alan G.

More information about the Tutor mailing list