Question

I'm looking for a way to return True or a string, and later use that info to show something or not. Here is my code:

def time_remaining(self):
    timer = self.timer
    now = datetime.datetime.utcnow().replace(tzinfo=utc)
    if timer < now:
        return True
    else:
        #Returns a timedelta in string
        return game_logic.timedelta_format(timer - now)

Then later on I use:

if time_remaining():
    possible = True
else:
    possible = False

return render(request, 'training.html',{'possible': possible})

and finally in my template:

{% if possible %}
    <some html>
{% else %}
    <different html>
{% endif %}

Somehow I always end up at the even if the time_remaining returns the string instead of True

How can I fix this problem?

Was it helpful?

Solution

In Python non-empty strings also evaluate as True:

>>> bool('foo')
True
>>> bool('')
False

So no matter what your time_remaining function returns, it will always be evaluated as True in your if statement.

You probably want to use something like:

time_remaining() == True

Or perhaps even have time_remaining return False or None if there is no time left (especially if you are only going to use the output of time_remaining in your if statement).

OTHER TIPS

time_remaining() == True:

Seems that does the trick :) Figured it always returns something Some explanation what exactly is going on would be still apreciated

Your time_remaining function always returns a value that evaluates to True in the if statement. So possible will always be True.

Add some extra logic in your second code block to do the behaviour you expect, such as testing the value of the time delta.

Function outputs should be of the same type, with the special value 'None' to tell an empty output (although I cannot find any reference for this statement...).

So, you should do:

if timer < now:
    return game_logic.timedelta_format(empty_timedelta) 
else:
    #Returns a timedelta in string
    return game_logic.timedelta_format(timer - now)

or:

time_limit = min(timer, now) #if 'min' applies
return game_logic.timedelta_format(timer - time_limit ) 

or:

if timer < now:
    return None
else:
    #Returns a timedelta in string
    return game_logic.timedelta_format(timer - now)

or return a couple of values: the first tells the kind of result, the second is the actual result

if timer < now:
    return (True, None)
else:
    #Returns a timedelta in string
    return (False, game_logic.timedelta_format(timer - now))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top