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?
from python import Python

def do_numpy_stuff(ar: PythonObject) -> PythonObject:
ar.__iadd__(3)
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(ar: PythonObject) -> PythonObject:
ar.__iadd__(3)
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)
I would expect the outside function ar print to print the modified ar, because the ar is passed as object reference. But I got this:
> 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:
[[ 3 4 5 6 7]
[ 8 9 10 11 12]
[13 14 15 16 17]]
outside function:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
> 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:
[[ 3 4 5 6 7]
[ 8 9 10 11 12]
[13 14 15 16 17]]
outside function:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
8 replies