tzl
tzl
MModular
Created by tzl on 5/14/2024 in #questions
Why is this in-place operation not modifying the Python object in-place?
8 replies
MModular
Created by tzl on 5/14/2024 in #questions
Why is this in-place operation not modifying the Python object in-place?
What I was expressing in the original post was more similar to when PythonObject is a list. This would mutate the Python object internally.
from python import Python

def do_py_stuff(li: PythonObject) -> PythonObject:
li.append(1)
print("inside function:\n", li)

return li


fn main() raises:
var li = Python.list()
print(li)

print("do_py_stuff:")
do_py_stuff(li)
print("outside function:\n", li)
from python import Python

def do_py_stuff(li: PythonObject) -> PythonObject:
li.append(1)
print("inside function:\n", li)

return li


fn main() raises:
var li = Python.list()
print(li)

print("do_py_stuff:")
do_py_stuff(li)
print("outside function:\n", li)
mojo do_numpy_stuff.mojo
[]
do_py_stuff:
inside function:
[1]
outside function:
[1]
mojo do_numpy_stuff.mojo
[]
do_py_stuff:
inside function:
[1]
outside function:
[1]
8 replies
MModular
Created by tzl on 5/14/2024 in #questions
Why is this in-place operation not modifying the Python object in-place?
I understand with inout it would be mutated. But inout is when regarding a Mojo variable, one could reassign this variable (lvalue) to anything of the same type:
from python import Python

def do_numpy_stuff(inout ar: PythonObject) -> PythonObject:
ar = Python.list()
print("inside function:\n", ar)

return ar


fn main() raises:
var np = Python.import_module("numpy")
var ar = np.arange(15).reshape(3, 5)
print(ar)

print("do_numpy_stuff:")
do_numpy_stuff(ar)
print("outside function:\n", ar)
from python import Python

def do_numpy_stuff(inout ar: PythonObject) -> PythonObject:
ar = Python.list()
print("inside function:\n", ar)

return ar


fn main() raises:
var np = Python.import_module("numpy")
var ar = np.arange(15).reshape(3, 5)
print(ar)

print("do_numpy_stuff:")
do_numpy_stuff(ar)
print("outside function:\n", ar)
prints out
> mojo do_numpy_stuff.mojo
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
do_numpy_stuff:
inside function:
[]
outside function:
[]
> mojo do_numpy_stuff.mojo
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
do_numpy_stuff:
inside function:
[]
outside function:
[]
Any PythonObject would do. This is a separate point from what I was trying to show up there in the orignal post.
8 replies