tags:

views:

26

answers:

2

Hi all,

I was wondering if there was a way that you could get init code to run upon importing a .NET assembly using clr.AddReference(), in the same way that importing a python file executes the init.py code that resides in the same directory. Thanks in advance!

A: 

It is not possible.

The only way is to change the clr.AddReference method. As IronPython is open source it should be easy.

Lukas Cenovsky
+1  A: 

It's not possible from clr.AddReference, as far as I know.

If your assembly has an IronPython module, you can run code when it is imported (a la __init__.py). An IronPython module is pretty simple to set up:

[assembly: PythonModule("mymodule", typeof(MyModule))]
public static class MyModule
{
    [SpecialName]
    public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
        // module initialization code
    }

    // variables, functions, classes, etc. that appear in the module
}

Don't get confused by the "Reload" part of the name; it's called when the module is loaded as well as every time it is reloaded.

If your assembly will be used outside of IronPython, you can put this module in a separate assembly that references your original module. If you want some examples of how to write modules, check out the source to the IronPython.Modules project on http://ironpython.codeplex.com.

Jeff Hardy