I think it's a bit weird question to ask.
The thing is that while I was studying some parts of django code I came across something I've never seen before.
According to Copy Difference Question and
It's usage in dictionary we can create two dictionary with same reference.
The question is what is the purpose of setting a shallow copy of a dictionary to itself?
Code:
django.template.backends.base
params = {
'BACKEND' = 'Something',
'DIRS' = 'Somthing Else',
}
params = params.copy()
Shallow copies are useful when you want to make copies of classes that share one large underlying data structure or set of data.
In the case of shallow copy, a reference of an object is copied into another object. It means that any changes made to a copy of an object do reflect in the original object.
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.
The problem with the shallow copy is that the two objects are not independent. If you modify the one object, the change will be reflected in the other object. A deep copy is a fully independent copy of an object. If we copied our object, we would copy the entire object structure.
The relevant part or django.template.backends.base.py looks like this:
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)))
The dictionary params
in def __init__(self, params):
will be copied to a new dictionary params = params.copy()
. It just uses the same name. Therefore, the old object cannot be accessed any more via this name. In the next steps the new local dictionary is modified but the original one stays unchanged.
Doing self.params = params
, instead of params = params.copy()
would have a very different effect. In this case self.params
would be just a second name for the object behind params
. Since it is a dictionary and mutable, all changes to self.params
would effect params
. params.pop('NAME')
removes the key NAME'
from the dictionary. Actually, there is a check that it is empty: params.pop('NAME')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With