[IronPython] Pass Module Functions as Parameters to Functions

Steve Dower s.j.dower at gmail.com
Thu Feb 10 21:31:16 CET 2011


There are two options here. You can either pass the function directly:

    def do_something(self, myFunction):
        myVar = someFunction(myFunction)

    obj.do_something(obj.function)

Or you can pass the name as a string and use getattr:

    def do_something(self, myFunction):
        myVar = someFunction(getattr(self, myFunction))

    obj.do_something("function")


getattr will raise an exception if the attribute does not exist, or
you can pass a third parameter as a default value. If you want to
ensure that it is actually a function, you can do it like this (or
substitute if statements for assertions, but I like assertions):

    def do_something(self, myFunction):
        assert hasattr(self, myFunction)
        assert hasattr(getattr(self, myFunction), '__call__')

        myVar = someFunction(myFunction)

(Obviously there are multiple getattrs going on here - if performance
is a concern you should be running with "ipy.exe -OO" to ignore the
assertions or using a different language.)


On Fri, Feb 11, 2011 at 06:50, Andrew Evans <evans.d.andrew at gmail.com> wrote:
> I am having trouble figuring out the correct way of doing this. I am using
> the module cmd.
>
> Anyway this is what I do
>
> import myModule
>
> class Example(cmd.Cmd):
>     def __init__(self):
>         cmd.Cmd.__init__(self)
>         self.prompt = '>>> '
>
>     def do_something(self, myFunction):
>         myVar = someFunction(myModule.myFunction)
>
>
> trying to use myFunction as a keyword argument so when I run it I can use a
> function as argument
>
>>>> something Test()
>
> But the syntax I am using isn't right or something
>
> Any ideas?
>
> *cheers
>
>
>
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>
>



More information about the Ironpython-users mailing list