[IronPython] Moving/Copying a PythonFunction to a different scope

Jeff Slutter jslutter at reactorzero.com
Mon Feb 2 18:52:32 CET 2009


My situation is that I have a .py file that defines a function. In this
function it makes reference to some variables that aren't defined in its
scope:

(in a very simple way, it is like this -- a lot more is going on, but it
isn't relevant)

import MyModule

def TestFunction(x):
  return SomeClass(x).Execute(SomeVar);



Later on, I create a new ScriptScope for my app, and I want to import
"TestFunction" in to it so I can use it. I'm trying to avoid actually
executing the .py file that defined it (it would import MyModule into my
scope and I don't want that for example).
I *do* compile the .py file when I first encounter it, and I can use
GetVariable to extract out the TestFunction object (as a PythonFunction).

Now, when I create my new ScriptScope, I actually define "SomeVar" (it
is unique to a ScriptScope), the variable used in TestFunction above. If
I were to SetVariable in my new ScriptScope and set the previously
extracted TestFunction, it will work -- except "SomeVar" isn't known to
TestFunction because it was created in a different ScriptScope, that
didn't have it defined (when I initially loaded the .py file).

I tried creating a new PythonFunction and passing it a CodeContext and
the function information from TestFunction to 'copy' it to my new
ScriptScope - but that functionality threw an exception as not
implemented (IP 2.0)

Is there some (multithread safe) way that I can either:
 a) copy TestFunction to my new ScriptScope and have it run in my scope
 b) find some way to get SomeVar defined for it (so that if another
ScriptScope, running in another thread, calls TestFunction, they want
cross their SomeVar values)

I *KNOW* this all sounds complicated and crazy, and that there are
probably cleaner ways of doing this, but based on other restrictions of
the application, I can not see a way of doing things without doing them
in this structure (the .py file referenced in this email is actually a
pseudo "plug-in" to my app, and SomeVar is some state information that I
need to implicitly pass around into that Execute call).

I thought maybe something with decorators, but they are done at function
definition and so I don't think that is of use.

Thanks,
-Jeff




More information about the Ironpython-users mailing list