0

I have a function that looks like this:

def getCurrentShow(hour=(localtime().tm_hour),day=datetime.datetime.now().strftime('%A')):
        return Schedule.objects.get(hour=hour,day=day).show

so I can call it with or without a time or day. My problem is that when I call it with no arguments ie:

print getCurrentShow()

It always returns the same object when run from the same python instance(if I have a python shell running and I wait for an hour and start a new shell without quiting the old one for example, I can run it and get different results between the shells(or webserver) but the function always returns the same value once in the same shell).

I'm guessing python caches the results of functions called without arguments somehow? any way to get around this without rewriting all my calls to getCurrentShow to something like

Schedule.objects.get(hour=(localtime().tm_hour),day=datetime.datetime.now().strftime('%A')).show

?

Thanks.

1 Answer 1

6

The default values for your function arguments are calculated the first time the function is loaded by the interpreter. What you want is the following:

def getCurrentShow(hour=None, day=None):
    hour = hour or localtime().tm_hour
    day = day or datetime.datetime.now().strftime('%A')
    return Schedule.objects.get(hour=hour, day=day).show

The way this works is that the or operator returns the first operand that bool(operand) != False. Example:

>>> None or 5
5
>>> None or datetime.now()
datetime.datetime(2011, 6, 6, 11, 25, 46, 568186)
>>> 10 or datetime.now()
10

In this way you can make the default value for your arguments None, and they'll default to the current time, or the caller can pass in their own value which will override the default.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for being so fast! This looks like it works so far, I'll let you know in 15 minutes if it solved it fully! P.s. Just saw your name, That's my name LoL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.