What is the role of __deepcopy__ in Python class and Django widget

8 views
Skip to first unread message

Paul

unread,
Nov 4, 2017, 5:48:18 AM11/4/17
to Django users

First, I know how copy and deepcopy from copy module work for a list.


I'm interested the role of __deepcopy special method inside a class.


I need to create custom widgets in Django and I try to understand the python code behind.


class Widget(metaclass=MediaDefiningClass):

    needs_multipart_form = False  # Determines does this widget need multipart form
    is_localized = False
    is_required = False
    supports_microseconds = True  # for data and time values

    def __init__(self, attrs=None):
        if attrs is not None:
            self.attrs = attrs.copy()
        else:
            self.attrs = {}

    def __deepcopy__(self, memo):
        obj = copy.copy(self)
        obj.attrs = self.attrs.copy()
        memo[id(self)] = obj
        return obj

What is happening with __deepcopy__ when I make an instance of Widget, or and instance of a subclass of Widget ? Looks like is making a shallow copy of attributes and the object itself , but what is the purpose ?

Reply all
Reply to author
Forward
0 new messages