Re: [Tutor] What Eval() Hath Men Wrought

Magnus Lycka magnus at thinkware.se
Thu Jun 24 12:34:33 EDT 2004


Theresa Robinson wrote:
> The C way to do it is to pass in a pointer to a function.  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.  The Matlab way to do
> it is to pass a string that contains the function name, and to use the
> Matlab feval function, which is similar to the Python eval but nicer since
> you don't have to construct the whole string yourself, but instead can use
> the form feval('function_name',argument).  This works but is bad because

It's even simpler than that in Python with the old "apply" function,
but you don't need that either... That's obsolete.

> 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.

Python obviously doesn't have static typing, but in all it's much better
than C for things like that. There are things that might not be discovered
until runtime, but you can write much, much more generic and simple code
for the kind of things you describe.
 
> What is the right way to do this in Python?  Where can I learn how to do
> it?

The C way, but skip the pointer thingie. Just do it. It's trivial. I will 
even refuce to show any example. Just imagine that it is as simple as it 
could possibly be. If you don't get it to work, it's probably because you 
don't believe it can be that simple, and you try to convolute your code. ;)

Almost everything is an object in Python, and objects are dealt with in a
very uniform way.

Look at the chapter about functions in the Python Tutorial, and be amazed
about how easy it is to write generic code that will pass any number of
positional or named arguments to a function.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list