일반적으로 깊은 사본을 만드는 일은 간단하지 않다는 점에 주의하라. 객체 안에 순환 참조가
있으면 단순 알고리즘은 무한 루프에 빠질 수 있다.
deepcopy()
함수는 순환 참조를 제대로
처리하고자 이미 복사한 객체에 대한 참조를 기억한다. 순환 참조를 깊게 복사하는 예는 [예제
6
-
10
]과 같다.
예제
6-10
순환 참조.
b
가
a
를 참조한 후
a
의 뒤에 연결되는데,
deepcopy
()
는
a
를 제대로 복사한다.
>>> a = [10, 20]
>>> b = [a, 30]
>>> a.append(b)
>>> a
[10, 20, [[...], 30]]
>>> from copy import deepcopy
>>> c = deepcopy(a)
>>> c
[10, 20, [[...], 30]]
게다가 깊은 복사가 너무 깊이 복사할 때도 있다. 예를 들어
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.