13

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.

Tristan
  • 6,776
  • 5
  • 40
  • 63

2 Answers2

13

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
  • 117,631
  • 17
  • 236
  • 300
  • 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 Feb 16 '10 at 00:07
6

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
  • 1,738
  • 12
  • 16
  • I'm afraid that `typeof` 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 Feb 15 '10 at 23:57
  • (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 Feb 15 '10 at 23:59
  • 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 Feb 16 '10 at 00:09
  • @Tomas: Ah, you are right... of course, if modules were types, functors wouldn't be far behind, would they? – pblasucci Feb 16 '10 at 02:22