Django 中不寻常的 setdefault

Atm*_*aks 1 python django dictionary

这是Django 的身份验证模型(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)
Run Code Online (Sandbox Code Playgroud)

为什么要设置一个键值对并在之后立即检查它?在什么情况下会满足这些条件?

AKS*_*AKS 5

setdefault仅当键不存在于字典中时才设置值。函数的调用者仍然可以传递extra_fields一些id_staff或 的值is_superuser

什么这个函数是在创建一个超级用户,如果调用函数未提供再设置任何值is_staff,并is_superuser都以真为这个用户。

但是,如果提供了值,则检查这些值是否存在True,否则引发异常。