Here's a piece of code from Django's authentification models (UserManager):
def create_superuser(self, username, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, email, password, **extra_fields)
Why set a key-value pair and check it immediately afterwards? In what scenario would these conditions be met?
setdefault sets the value only if the key is not already present in the dict. The caller of the function could still pass extra_fields with some values of id_staff or is_superuser.
What this function does is that while creating a superuser if the calling function is not providing any values then set is_staff and is_superuser both to True for this user.
But, if the values are provided then check if those are True and raise exceptions otherwise.