lcompilers / lpython

Python compiler
https://lpython.org/
Other
1.37k stars 157 forks source link

Bug: Assignment `b = a` stores a deep copy of the mutable data structure `a` in `b` instead of a shallow copy #2637

Open kmr-srbh opened 3 months ago

kmr-srbh commented 3 months ago

In CPython, an assignment b = a stores the reference of a in b. This means that modifying a will reflect the changes in b. LPython however, creates a deep copy of the data structure, hence making it an independent entity.

from lpython import i32

main_list: list[i32] = [1, 2, 3, 4]
copy_list: list[i32] = main_list

print("Main List:", main_list)
print("Copy List:", copy_list)

main_list.append(5)

print("Main List:", main_list)
print("Copy List:", copy_list)

CPython

(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ python3 ./examples/example.py
Main List: [1, 2, 3, 4]
Copy List: [1, 2, 3, 4]
Main List: [1, 2, 3, 4, 5]
Copy List: [1, 2, 3, 4, 5]

LPython

(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
Main List: [1, 2, 3, 4]
Copy List: [1, 2, 3, 4]
Main List: [1, 2, 3, 4, 5]
Copy List: [1, 2, 3, 4]