python/django function returning identical value every time
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:
p开发者_JAVA百科rint 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.
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.
精彩评论