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,
If I run this, it will show the following message:
Question originally posted by HKTonyLee on SO: https://stackoverflow.com/questions/77063677/how-to-pass-mojo-function-to-python-in-python-interop
Stack Overflow
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_p...
8 Replies
Not tested so sorry if it’s wrong, but there may be a way to turn the mojo ‘object’ (5) into a PythonObject (5)
Hi @Mahmoud Abduljawad you need to pass a concrete type like Int, String etc so it knows how to convert it. Also you need to use a function that actually exists e.g:
The function returns an object created by python lib, effectively,
PythonObject
. If I set the return type of function as such, marshalling fails.
This is another example where this fails:
Error:
Oh you want to pass a callback in Mojo to Python class? You can't do that at the moment sorry, interesting concept though
I see, @Jack Clayton. I'm trying to offload some of the logic from Python to Mojo to compare performance gains in such cases. Of course this is the simplest explanation, however, I was hoping to start building a sample web application with Mojo built on top of
AIOHTTP
which won't be possible at the moment due to this limitation.
Do I need to open an issue to track this?Congrats @Mahmoud Abduljawad, you just advanced to level 1!
Yeah I think it's a good one for https://github.com/modularml/mojo/discussions/new?category=ideas
I'm sure of the difficulty level of implementing something like that but I'd be interested to see what the engineers have to say
GitHub
Allow passing Mojo function as argument to Python function · modula...
Currently, Mojo doesn't support passing Mojo functions as arguments to Python functions. Certain Python libs accept a callable as an argument which runs side effects, and Python interop in Mojo...