[Django]-Which is a better way to check request conditions?

2👍

I’ve just grepped the whole (current git) source of django, and hadn’t found a single occurrence of all three conditionals you mentioned.

And you are perfectly right with the one condition sufficing it as long as you can assume that all the three dictionaries are set. And looking at django code, I believe you can assume that.

Edit: also the django documentation suggests that those dictionaries will always be set.

6👍

It can be acheived only by checking
request.META.get('HTTP_REFERER')
and
request.REQUEST.get('next')
instead of checking it for request.POST or request.GET

👤PiyusG

2👍

There is one (hypothetical) case where your solution would fail:

>>> request.POST = None
>>> 'next' in request.POST
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'NoneType' is not iterable

But if you can be sure that request.POST will never be None, then your solution would be OK.

It’s just a little slower in the case of an empty dictionary because the if 'foo' in request.POST check can be skipped if the (fast) test for emptiness already fails. On the other hand, it will be faster if the dictionary is not empty.

>>> import timeit
>>> timeit.timeit(setup="a = {}", stmt="if a and 'next' in a: pass")
0.028279806566242852
>>> timeit.timeit(setup="a = {}", stmt="if 'next' in a: pass")
0.04539217556517272
>>> timeit.timeit(setup="a = {'foo':'bar'}", stmt="if a and 'next' in a: pass")
0.07471092295071458
>>> timeit.timeit(setup="a = {'foo':'bar'}", stmt="if 'next' in a: pass")
0.045236056421884996
>>> timeit.timeit(setup="a = {'next':'bar'}", stmt="if a and 'next' in a: pass")
0.0851067469988891
>>> timeit.timeit(setup="a = {'next':'bar'}", stmt="if 'next' in a: pass")
0.0520663758715898

So I guess this is a question of micro-optimisation. In that case, I invoke the Zen of Python: Explicit is better than implicit.

Leave a comment