1

What to do with unused variables in Django (I speak mostly about class based views)?

 def post(self, request, *args, **kwargs):
        # request, args, kwargs are not used in this post method
        ..
        return ..

Is it safe to del them ?

In here I also see, that *_ can be used for things I don't care.

Why? For the sake of cleaning the code and avoiding IDE warnings.

I can safely del *args and **kwargs, but how about request? request I can acces it later using self.request, when using a class based view - actually I do that, but can I be sure that I will have no problem?

I see here that django request is immutable, but no in all cases.

My question is, what do do with them?

Community
  • 1
  • 1
sergiuz
  • 5,353
  • 1
  • 35
  • 51

1 Answers1

2

In terms of calling them - you don't use them, as you probably already know. *args and **kwargs are entirely optional, so don't pass them. In the example above, you can call that view method with just a request object.

In terms of writing them and clean code: If these are your CBVs, leave them off the declaration; if they're arguments inherited from the generic base class, then surely you won't see them in your code anyway?

If you're asking from a garbage collection point of view, then they'll expire after the view function has run and is no longer referenced by the view namespace. Ned's coverage of variables in python is always relevant.

In terms of idiomatic python, explicitly deling the variables would be quite unusual, and make the code significantly less readable. It also won't, for instance, free the memory, although I appreciate that wasn't one of the reasons you were asking.

On the specifics of the request object - the request object is required to use render in Function based views. In CBVs, it's an attribute rather than a variable, for the semantic difference that makes, but even if you're not using it directly, Django needs the request object to generate the HttpResponse.

Also, the generic view base class docs have further details on that flow down through the stack.

Withnail
  • 3,128
  • 2
  • 30
  • 47