Use assert in normal code
<p>I'm writing a python function to validate a token from an email. In the email, there is a url with the endpoint of it. I have two url parameters, the token and email address. In my endpoint I have to check : </p>

<ul>
<li>if the parameters are in the URL</li>
<li>if there is a associate token in the database</li>
<li>if it corresponds to the user email</li>
<li>if the token is still valid (expires after 2 days)</li>
<li>if it has already been used</li>
</ul>

<p>I choose to wrap all those checks in a <code>try except</code> block, I will always return the same error "invalid token" so I don't have to precisely check individual error. I used the function <code>assertFalse</code> and <code>assertEqual</code> that will raise an exception if it's not correct.</p>

<pre><code>try:
    # pull from url
    email = request.GET['email']
    value_token = request.GET['token']
    # test if valid
    token = EmailValidationToken.objects.get(token=value_token)
    assertFalse(token.consumed)
    assertEqual(email, token.user.email)
    assertFalse(token.is_expired())
except:
    pass # return error
</code></pre>

<p>I like the way I did it because it's super clean.
Is it a good practice ? Is there other solution for this problem ?</p>

<p>No, using <code>assert</code> for control flow rather than debugging is poor practice, because assertions can be turned off. Just use an ordinary <code>if</code> statement.</p>

<pre><code># pull from url
email = request.GET['email']
value_token = request.GET['token']
# test if valid
token = EmailValidationToken.objects.get(token=value_token)
if token.consumed or email != token.user.email or token.is_expired():
    pass # return error
</code></pre>

<p>If you absolutely insist on controlling your program's flow by raising an error (which is a valid thing to do in some cases), do so with <code>raise</code>, e.g. <code>if condition: raise TypeError</code>.</p>

python assert