[IronPython] register module with an IronPython engine

Dino Viehland dinov at exchange.microsoft.com
Thu Oct 26 18:08:22 CEST 2006

Ahh, got it... From your engine you can access SystemState (engine.Sys) and from there you can publish your object in the module table:

engine = new PythonEngine();
engine.Sys.modules['myapp'] = new MyAppProxy();

this is equivalent to the Python code:

import sys
sys.modules['myapp'] = MyAppProxy()

from there anyone importing myapp should get the MyAppProxy object.

-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Fredrik Lundh
Sent: Thursday, October 26, 2006 2:43 AM
To: Discussion of IronPython
Subject: Re: [IronPython] register module with an IronPython engine

Dino Viehland wrote:

> You can apply the PythonModule to your assembly specifying the type
> that corresponds with the module type.  In 1.0.1 our site.py will load any
> DLLs in the "DLLs" directory and the module will be available for you to
> import.  The type that PythonModule references should be a static type
> (no instance members).

I was probably a bit unclear, but I want to inject the module from inside
the embedding application.  i.e. something like

            engine = new PythonEngine();
            engine.AddObjectAsModule("myapp", new MyAppProxy());
                 "import myapp\n" +

where MyAppProxy is some suitable object that has a "ping" method.  I
can easily do

            engine = new PythonEngine();
            engine.GlobalsAdd("myapp", new MyAppProxy());

but that only makes "myapp" available for executed code, not for other
modules, and it makes it harder to write code that can run in other con-
texts (in this case, a CPython prototype/test harness).

we've currently solved this by using a separate python module to make
the contents of the global "myapp" available as a module:

            engine = new PythonEngine();
            engine.GlobalsAdd("_myapp", new MyAppProxy());
            engine.Execute("import myapp; myapp.init(_myapp)");

            (where myapp.init copies relevant attributes to module globals)

but I would like to get rid of that extra layer, if possible.

(I'm probably missing something trivial here)

cheers /F
users mailing list
users at lists.ironpython.com

More information about the Ironpython-users mailing list