Home > database >  How do I make a function return another function
How do I make a function return another function

Time:01-30

How do I make a function that returns another function, but without an if statement?

For example:

def mainFunction():
    if addRequirement(10) == False: return

def addRequirement(r):
    if r > 0: return True
    else: return False

The above, except without the 'if xyz == False: return' part, just 'addRequirement(10)'

Thanks,

EDIT 1:

I should have mentioned that I'm writing a discord bot, and that the bot's command has a requirement. The addRequirement function just cancels the main async function if it isn't met.

CodePudding user response:

Not sure I fully understand the requirement here but perhaps:

def mainFunction():
    return addRequirement(10)

def addRequirement(r):
    return r > 0

CodePudding user response:

If you mean that you want to write a command to return a value based on a condition without using the 'if' statement, you can use inline if as follows:

def addRequirement(r):
    return something if anyConditions else somethingElse

But, if you mean you just wanna have two functions that the addRequirement return one of these functions and the mainFunction runs that, this is the solution:

def mainFunction():
    f = addRequirement(-10)
    f()
    f = addRequirement(10)
    f()

def positiveFunction():
    print("Positive")

def negativeFunction():
    print("Negative")

def addRequirement(r):
    return positiveFunction if r>0 else negativeFunction

mainFunction()

And the output of this code is:

Negative
Positive
  •  Tags:  
  • Related