Mahmoud Abduljawad
Mahmoud Abduljawad
MModular
Created by Mahmoud Abduljawad on 9/17/2023 in #questions
How to store PythonObject in DynamicVector?
I'm trying the following:
let module = Python.import_module("my_module")
let dv = DynamicVector[PythonObject]()
let result = my_module.my_func()
dv.push_back(result)
let module = Python.import_module("my_module")
let dv = DynamicVector[PythonObject]()
let result = my_module.my_func()
dv.push_back(result)
And getting:
cannot bind generic !mlirtype to memory-only type 'PythonObject'
cannot bind generic !mlirtype to memory-only type 'PythonObject'
I tried different combinations, but as long the type is non-imperative type, this won't work. What is a workaround for this?
6 replies
MModular
Created by Mahmoud Abduljawad on 9/9/2023 in #questions
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 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()
# 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
$ 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
13 replies