Is there a way to pass a F# method to a Python function?

Viewed 116

I am trying to call a python function from F#. So far, I managed to call a simple Python function (e.g: to print a string). The problem is that I can't manage to pass a F# method to my Python function and call it from here.

Program.fs

let printMsg () = Console.WriteLine "Print from F#"

[<EntryPoint>]
let main argv =
    Environment.SetEnvironmentVariable ("PATH", pythonPath + Environment.GetEnvironmentVariable "PATH")
    PythonEngine.Initialize ()

    let import = PythonEngine.ImportModule "HelloWorld"
    let helloWorld = import?HelloWorld()

    helloWorld?exec(printMsg)

    PythonEngine.Shutdown ()

    0

Helloworld.py

class HelloWorld:
    def __init__(self):
        print("__init__")

    def exec(self, printMsg):
        printMsg()

But I get Python.Runtime.PythonException: 'TypeError : object is not callable' on the helloWorld?exec(printMsg) line of Program.fs, caused by the call to printMsg() from Python.

1 Answers

You need to construct a delegate from your F# function, then pass it to Python. I think System.Action(printMsg) should suffice.

Related