[Numpy-discussion] function name as parameter
josef.pktd@gmai...
josef.pktd@gmai...
Wed Oct 20 08:51:09 CDT 2010
On Wed, Oct 20, 2010 at 9:46 AM, Zachary Pincus <zachary.pincus@yale.edu> wrote:
>> I'm trying to write an implementation of the amoeba function from
>> numerical recipes and need to be able to pass a function name and
>> parameter list to be called from within the amoeba function. Simply
>> passing the name as a string doesn't work since python doesn't know it
>> is a function and throws a typeerror. Is there something similar to
>> IDL's 'call_function' routine in python/numpy or a pythonic/numpy
>> means
>> of passing function names?
>
> Just pass the function itself! For example:
>
> def foo():
> print 6
>
> def call_function_repeatedly(func, count):
> for i in range(count):
> func()
>
> call_function_repeatedly(foo, 2) # calls foo twice
>
> bar = foo
> bar() # still calls foo... we've just assigned the function to a
> different name
>
>
> In python, functions (and classes, and everything else) are first-
> class objects and can be assigned to variables, passed around, etc,
> etc, just as anything else.
This is the best way, but if you want to pass the function name as
string, then you need to get the function with getattr
for example, scipy has code like this
def func(distname, args):
distfn = getattr(scipy.stats, distname)
distfn.rvs(args)
func('norm')
Josef
>
> However, note that scipy.optimize.fmin implements the Nelder-Mead
> simplex algorithm, which is (I think) the same as the "amoeba"
> optimizer. Also you might be interested in the openopt package, which
> implements more optimizers a bit more consistently than scipy.optimize.
>
> Zach
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list