vendredi 22 mars 2019

Function with different behavior depending on amount of input args

I want to create a function which will check if it is a correct hour to make an action, but I want it to be flexible and check condition for every pair of args given as an input to function. I wrote some code how it should look like in theory and now I'm trying to figure out how to write this in code.

def report_time(greater_than1=0, lower_than1=24, 
                greater_than2=0, lower_than2=24, 
                greater_than3=0, lower_than3=24, 
                ...
                greater_thanN=0, lower_thanN=24):    
    if greater_than1 < datetime.now().hour < lower_than1:
        logger.info('Hour is correct')
        return True

    if greater_than2 < datetime.now().hour < lower_than2:
        logger.info('Hour is correct')
        return True

    if greater_than3 < datetime.now().hour < lower_than3:
        logger.info('Hour is correct')
        return True

    ...

    if greater_thanN < datetime.now().hour < lower_thanN:
        logger.info('Hour is correct')
        return True

Examples of usage:

foo = report_time(16, 18)
foo = report_time(16, 18, 23, 24)
foo = report_time(16, 18, 23, 24, ..., 3, 5)

Aucun commentaire:

Enregistrer un commentaire