Search code examples
pythonlambdapython-datetime

Lambda Function to return different value using parameters


I would like to use a lambda function to return values. This could be handled in a function, however would prefer the use of lambda for this exercise. In general, I want to have the lambda return either a date or 0 by passing a second parameter.

import datetime
none_func=lambda x: 0 if x is None else x
print(none_func(None))
print(none_func(7))
print(none_func(datetime.datetime(2020,1,1)))
### Here, update the lambda function to take an additional parameters, like returns a date if None as well
none_func=lambda x: datetime.datetime(1900,1,1) if x is None else x
print(none_func(None))
print(none_func(7))

Updated for clarification:

I would like to convert the coalesce function to a lambda.

def coalesce(x,return_schema='int'):
    if x is None and return_schema=='int': return 0
    elif x is None and return_schema=='date': return datetime.datetime(1900,1,1)
    else: return x

print(coalesce(7))
print(coalesce(None))
print(coalesce(None,return_schema='date'))
print(coalesce(datetime.datetime.today(),return_schema='date'))

Solution

  • Use the function would be a better option, but if you want to convert it to lambda you can try something like this:

    import datetime
    
    f = lambda x,return_schema="int": 0  if x is None and return_schema=='int' else ( datetime.datetime(1900,1,1) if x is None and return_schema=='date' else x)
    print(f(7))
    print(f(None))
    print(f(None, return_schema='date'))
    print(f(datetime.datetime.today(), return_schema='date'))
    

    I hope it helps.