In python, returning an object created in a function body makes it a deep copy?

I will try to clarify:

For example, I create a function that locally creates a list and returns it. How does Python create a return list that exists outside the function body? Does it use "deepcopy" (or something like that)?

In [50]: def create_list():
    ...:     sublist1 = [1,2,3]
    ...:     sublist2 = [4,5,6]
    ...:     list_of_lists=[sublist1,sublist1,sublist2]
    ...:     return list_of_lists
    ...: 

In [51]: l=create_list()

In [52]: l
Out[52]: [[1, 2, 3], [1, 2, 3], [4, 5, 6]]

In [53]: l[0].append(4)

In [54]: l
Out[54]: [[1, 2, 3, 4], [1, 2, 3, 4], [4, 5, 6]]

Here, the returned list lstill contains sublists. And l[0]and l[1]still refer to the same sublist (which is Python's usual behavior). Thus, the list and its structure were copied.

And if I call again create_list():

In [55]: l2=create_list()

In [56]: l2
Out[56]: [[1, 2, 3], [1, 2, 3], [4, 5, 6]]

In [57]: l
Out[57]: [[1, 2, 3, 4], [1, 2, 3, 4], [4, 5, 6]]

l2, l , , , , , .

, : Python deepcopy - , l? , , ? ( , )

, . ,

+4
3

, - " , sublist1 [1, 2, 3]".

[1, 2, 3]. .


, , @functools.lru_cache, :

>>> @lru_cache()
... def create_list():
...     sublist1 = [1,2,3]
...     sublist2 = [4,5,6]
...     list_of_lists=[sublist1,sublist1,sublist2]
...     return list_of_lists
...
>>> l = create_list(); l
[[1, 2, 3], [1, 2, 3], [4, 5, 6]]
>>> l[0].append(4); l
[[1, 2, 3, 4], [1, 2, 3, 4], [4, 5, 6]]
>>> create_list()
[[1, 2, 3, 4], [1, 2, 3, 4], [4, 5, 6]]

python

+2

, .

, . , .

class Some_Class (object):
    prop_x = None
    def __init__(self, prop_x ):
        self.prop_x = prop_x
    def __repr__(self):
        return "prop_x = "+repr (self.prop_x)

def fx ():
    dict_x = { "k1" : "v1" }
    print hex ( id (dict_x) )
    obj1 = Some_Class ( prop_x = dict_x )
    print hex ( id (obj1.prop_x) )
    print "obj1 is "+repr( obj1 )
    return obj1

recv_obj = fx ()

print "recv_obj is "+repr( recv_obj ) 
print hex ( id (recv_obj.prop_x) ) 

0xdfaae0
0xdfaae0
obj1 is prop_x = {'k1': 'v1'}
recv_obj is prop_x = {'k1': 'v1'}
0xdfaae0 

A dict, dict_x, prop_x Class obj1. , soft copy. prop_x dict_x.

obj1 , dict_x , , , 0xdfaae0, - prop_x recv_obj, , dict { "k1" : "v1" } .

+2

Variables in Python are pointers to objects. Thus, the function returns a pointer to the object created in the function, eliminating the need to copy the returned values.

0
source

All Articles