Why install dictating a shallow copy to yourself?

I think this is a bit of a strange question. The fact is, while studying some parts of the django code, I came across something that I had never seen before. According to Copy the difference question and This usage in the dictionary, we can create two dictionaries with the same reference.

The question is, what is the purpose of installing a shallow copy of the dictionary for yourself?
Code:

django.template.backends.base

params = { 'BACKEND' = 'Something', 'DIRS' = 'Somthing Else', } params = params.copy() 
+5
source share
1 answer

The relevant part or django.template.backends.base.py is as follows:

 class BaseEngine(object): # Core methods: engines have to provide their own implementation # (except for from_string which is optional). def __init__(self, params): """ Initializes the template engine. Receives the configuration settings as a dict. """ params = params.copy() self.name = params.pop('NAME') self.dirs = list(params.pop('DIRS')) self.app_dirs = bool(params.pop('APP_DIRS')) if params: raise ImproperlyConfigured( "Unknown parameters: {}".format(", ".join(params))) 

params dictionary in def __init__(self, params): new params = params.copy() will be copied to the dictionary. It just uses the same name. Thus, the old object cannot be accessed through this name. In the next steps, the new local dictionary changes, but the original one remains unchanged.

Doing self.params = params instead of params = params.copy() will have a completely different effect. In this case, self.params will be just the middle name for the object behind params . Since it is a dictionary and modified, all changes to self.params will affect params . params.pop('NAME') removes the NAME' key from the dictionary. In fact, there is a check that it is empty: params.pop('NAME') .

+5
source

Source: https://habr.com/ru/post/1237969/


All Articles