Почему возвращаемое значение в python меняет тип после присвоения

Я озадачен этим куском кода. Код ниже является копией модуля renderer.py из django rest framework. Это заставило меня изучить много внутренних механизмов Python, но я все еще не могу понять, что происходит с возвратом / присвоением функции self.get_template_context.

def render(self, data, accepted_media_type=None, renderer_context=None):
    (...)
    print('1', id(data), data)
    context = self.get_template_context(data, renderer_context)
    print('4', id(context), context)
    (...)

def get_template_context(self, data, renderer_context):
    print('2', id(data), data)
    response = renderer_context['response']
    if response.exception:
        data['status_code'] = response.status_code
    print('3', id(data), data)
    return data

Итак, функция render вызывает get_template_context, передавая две переменные, data и renderer_context. Затем функция включает status_code в словарь данных перед возвратом (если исключение).

Я поместил несколько операторов печати, чтобы посмотреть, что происходит с этим маленьким кусочком кода:

ReturnDict - это объект, определяемый DRF следующим образом:

class ReturnDict(OrderedDict):
"""
Return object from `serializer.data` for the `Serializer` class.
Includes a backlink to the serializer instance for renderers
to use if they need richer field information.
"""

def __init__(self, *args, **kwargs):
    self.serializer = kwargs.pop('serializer')
    super().__init__(*args, **kwargs)

def copy(self):
    return ReturnDict(self, serializer=self.serializer)

def __repr__(self):
    return dict.__repr__(self)

def __reduce__(self):
    # Pickling these objects will drop the .serializer backlink,
    # but preserve the raw data.
    return (dict, (dict(self),))

Происходят две странные вещи, которые я не могу понять:

  1. Why the returned data, assigned to context is not the same type, or even the same structure as the data variable? Even more strange is the appearance of the key data inside of context.
  2. Where did kwargs key came from? It couldn't be accessed from data variable before the call. It is quite important for reversing some urls inside the template
Вернуться на верх