'determine returned object is copy or deepcopy
I was thinking , what if, i has function which returns of copy or deepcopy of object depend on some logic. for random now.
from copy import copy,deepcopy
from random import choice
def just_copies(obj_to_copy):
choices=[copy,deepcopy]
func = choice(choices)
return func(obj_to_copy)
some_list = [1,2,3,4,[5,6]]
copied_list = just_copies(some_list)
print("is ",copied_list," copy or deepcopy")
I was searching for answers, but can not find any other method than changing the list and seeing the outcome.
Solution 1:[1]
Loop through the original list and returned list, and test if any of the elements are different.
is_deepcopy = any(x is not y for x, y in zip(some_list, copied_list))
You need to use x is not y
because comparing lists with !=
compares the contents recursively, not object identity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |