Reputation: 2625
I have a function that uses a datetime object as default value:
from datetime import datetime, timedelta
from random import randint
def getTime(date = datetime.now()):
i = randint(1,300)
date = date - timedelta(seconds = i)
return date
Now, I need to check if the date variable inside the function was given by another function or was used the default one datetime.now(). If was used the default one, then subtract i seconds, else return the date that was given.
Upvotes: 1
Views: 79
Reputation: 8437
Assuming that you want "now" to be computed every time:
def getTime(date=None):
return date or datetime.now() - timedelta(seconds=randint(1,300))
Otherwise:
Introduce a default arg:
def getTime(date=None, _default=datetime.now()):
return date or _default - timedelta(seconds=randint(1,300))
Or create a decorator:
def just_return_if_provided(f):
def inner(date=None):
return date or f(date)
return inner
@just_return_if_provided
def getTime(date=datetime.now()):
return date - timedelta(seconds=randint(1,300))
Upvotes: 0
Reputation: 5443
You can do it as follows:
def my_function(date=None):
if date is None:
# The default is used
date = datetime.now()
...
Upvotes: 5