ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • copy - shallow and deep copy operations
    Python 2017. 6. 17. 03:16

    Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. 

    : Python에서 =(assignment) 연산자는 reference를 복사하지, object 자체를 복사하는 게 아니다. 


    copy.copy(x)

    Return a shallow copy of x.

    copy.deepcopy(x)

    Return a deep copy of x.

    [ Shallow copy와 Deep copy의 차이점 ]

    -> The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects like lists or class instances.).

    -> A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

    -> A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

    [ Deep copy가 가질 수 있는 문제점 ] 

    -> Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.

    -> Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies. 

    [ Tip ]

     list 안의 element가 일반적인 int일 경우, copy.copy()의 shallow copy만으로 충분하다. 



Designed by Tistory.