ModularM
Modular3y ago
12 replies
Mahmoud Abduljawad

How to pass Mojo function to Python in Python interop?

The question is how to pass Mojo function to Python in Python interop?

For example,
# This is main.mojo
from python.python import Python

def callback():
    return 5

def main():
  Python.add_to_path(".")
  let test_module = Python.import_module("lib")
  print(test_module.test_interop(callback))


# This is lib.py
def test_interop(func):
    return func()


If I run this, it will show the following message:

$ main.mojo
main.mojo:9:33: error: invalid call to '__call__': argument #1 cannot be converted from 'fn() raises -> object' to 'PythonObject'
  print(test_module.test_interop(callback))
        ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
main.mojo:1:1: note: function declared here
from python.python import Python
^
mojo: error: failed to parse the provided Mojo


Question originally posted by HKTonyLee on SO: https://stackoverflow.com/questions/77063677/how-to-pass-mojo-function-to-python-in-python-interop
Stack Overflow
The question is how to pass Mojo function to Python in Python interop?
For example,

This is main.mojo

from python.python import Python

def callback():
return 5

def main():
Python.add_to_p...
How to pass Mojo function to Python in Python interop?
Was this page helpful?