Skip to content
Advertisement

Passing parameter through function

I needed SQL-like DATEADD(https://learn.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-ver15) function to avoid using multiple if statements.

This is what I currently have:

def dateadd(interval, num, my_date):
    if isinstance(my_date, date):
        if interval == 'day':
            final_date = my_date + relativedelta(days = num)
        elif interval == 'month':
            final_date = my_date + relativedelta(months = num)
        return final_date
    else:
        'Not a date!'
        
today = dateadd('day', 0, datetime.today().date())
yesterday = dateadd('day', -1, today)

This is what I’m trying to achieve (to pass INTERVAL argument to dateadd function that would change parameter of relativedelta to days,months,years etc.):

def dateadd(INTERVAL, num, my_date):
    if isinstance(my_date, date):
        final_date = my_date + relativedelta(INTERVAL = num)
        return final_date
    else:
        'Not a date!'

Advertisement

Answer

That’s not how it’s done. Try this:

interval = {
    'month': num # or  'day': num
}
def dateadd(interval, my_date):
    if isinstance(my_date, date):
        final_date = my_date + relativedelta(**interval)
        return final_date
    else:
        return 'Not a date!'

Basically, you have to create a dictionary with parameter name as the key and parameter’s value as the key’s value. And then use ** to unpack the value in the function’s parameter.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement