[IronPython] How to dynamically define and call a function?

Gary Stephenson garys at ihug.com.au
Mon Sep 18 10:51:38 CEST 2006


hi,

I confess to being a newbie at this sort of thing in Python or IronPython, 
so I'm hoping that there is a simple answer to the subject question.

I started off trying to use standard "compile()" function and "exec" 
statement, but was unable to make it work, although I'm sure there must be a 
way. Is there?  How?

So then I tried the following instead:

    import IronPython
    from IronPython import Hosting

    s = "def myAdd(x,y):\n    return x+y\n"

    engine = Hosting.PythonEngine()
    mod = engine.CreateModule()
    engine.Execute(s,mod)

My understanding is that the above should have created a function named 
"myAdd" inside the newly minted "mod" module,  but if it did so I was unable 
to find any evidence of it.  How would I access/use it?

So then I modified the above to name the module and import it (even though 
this doesn't really meet my ultimate requirements):

    import IronPython
    from IronPython import Hosting

    s = "def myAdd(x,y):\n    return x+y\n"

    engine = Hosting.PythonEngine()
    mod = engine.CreateModule("testing",True)
    engine.Execute(s,mod)
    import testing

but alas this throws an "ImportError: No module named testing".   Why?

yrs in puzzlement,

gary 




More information about the Ironpython-users mailing list