[Django]-The difference in functions of `**kwargs` and `**initkwargs`

2👍

While kwargs is the conventional name, the main reason it is called initkwargs is to avoid name conflicts:

@classonlymethod
def as_view(cls, **initkwargs):
    """Main entry point for a request-response process."""
    ...

    def view(request, *args, **kwargs):  # defines kwargs
        self = cls(**initkwargs)         # uses initkwargs
        ...
        return self.dispatch(request, *args, **kwargs)
    ...
    return view

Note that the inner view function takes a **kwargs parameter. If the classmethod used the same name, the inner **kwargs would shadow the outer **kwargs, and the function wouldn’t be able to access the outer kwargs when instantiating cls.

Using the name initkwargs avoids this issue.

👤knbk

0👍

As a comment says, there is no difference between the two regarding the mechnics behind it. The important part is the **. That being said, I’d like to add the distinction from the two seems to comes from the fact that **initkwargs is use for class instanciation. Indeed, it is always use in conjunction with cls which normally stands for the first argument to class methods (PEP 8).

So even though there is not much difference between the two and that it may only be a good pratice, I would not say that this is irrelevant.

Leave a comment