4

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
4
  • 2
    I ran your code and get the same error. It can be inferred that a function defined in mojo even with def is different from that it is in Python. In error message, you can see its type is fn() raises -> object and the functions for Python in mojo is defined as PythonObject. The manual did not mention how do deal with this yet... But if you try a more simple way, it will work. Such as just call print in a python file. What if and how to use python to execute a mojo function(which is your callback) is still not clear. I will check if there is a corresponding issue in their github Commented Sep 8, 2023 at 8:00
  • 2
    I tried wrapping the function with PythonObejct but Mojo is unable to marshall it into Python value. Commented Sep 8, 2023 at 17:47
  • 1
    I've opened a issue here, hoping the contributors to response Commented Sep 9, 2023 at 3:45
  • 2
    The community has responded, and the answer is ”it is not supported yet“ Commented Sep 9, 2023 at 12:52

1 Answer 1

0

Sadly this isn't a feature supported in Mojo yet but it is something planned for sometime in the future.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.