tags:

views:

136

answers:

2

I'm trying to translate the following C# example, which constructs an IronPython module, to F#.

using System;
using IronPython.Runtime;

[assembly: PythonModule("my_module", typeof(MyModule))]

public static class MyModule {
    public static void hello_world() {
        Console.WriteLine("hello world");
    }
}

Using PythonModule allows from my_module import *, among other things.

I am having trouble figuring out how to apply the PythonModule attribute in F#. The F# documentation only talks about assembly attributes related to modules, and attached to do(). It's not clear to me how to define static classes that are interpreted as python modules, but I am not a C#/F#/IronPython expert.

+3  A: 

I don't have all the bits at hand to see if this works, but I would try

open System
open IronPython.Runtime

type MyModule = 
    static member hello_world() =
        Console.WriteLine("hello world")

module DummyModuleOnWhichToAttachAssemblyAttribute =
    [<assembly: PythonModule("my_module", typeof<MyModule>)>] 
    do ()

for starters.

Brian
This works. After adding the dll, `import my_module` works as expected. The dummy module seems a little funny, but I can live with that.
Tristan
+1  A: 

Haven't tested it but...

module MyModule 

open System
open IronPython.Runtime

let hello_world () =
    Console.WriteLine "Hello, World."

[<assembly: PythonModule("my_module", typeof<MyModule>)>] 
do ()

Same as Brian's, but without the dummy module.

pblasucci
I'm afraid that `typeof<MyModule>` won't work for `MyModule`, because it isn't a type, but a module (at least it didin't, last time I checked). This is an annoying limitation, because writing F# functions instead of static classes would be just great!
Tomas Petricek
(I would almost consider using some really nasty workaround to get this working, because it would be just so nice to write simple F# functions - e.g. you could write the `assembly` attribtue in C# and then use "ILMerge" to merge them into one)
Tomas Petricek
I also don't want to use a module directly, because I can't overload hello_world. By using static methods I get overloaded functions in Python.
Tristan
@Tomas: Ah, you are right... of course, if modules were types, functors wouldn't be far behind, would they?
pblasucci