0

WHY THERE IS AN IF CONDITION ? WHATS THE NEED OF AN IF COND IN THE MAIN FUNCTION ?

def callback(a, b): print('Sum = {0}'.format(a+b)) def main(a,b,f=None): print('Add any two digits.') if f is not None: f(a,b) main(1, 2, callback)

8th Aug 2022, 1:38 PM
Levi
Levi - avatar
1 Answer
+ 4
To ensure the argument passed through <f> parameter is not of a `None` type. The main() function is defined with 3 parameters, one of which was optional (f) with a `None` type as the optional parameter default value. This means main() can be invoked passing only 2 required arguments. Where such event happens, parameter will use default value `None` main( 1, 2 ) # None will be used as argument When parameter uses default value `None`, then it is not safe to call it like so f( a, b ) Because contains a non invocable object (None). Only when contains invocable object (e.g. function reference) the referenced function will be invoked, passing and arguments. To be safer, you can add a condition to verify whether refers an invocable object. This ensures that argument is an invocable object reference (e.g. reference to a function), and thus it makes sense to invoke it, assuming it also welcomes 2 arguments, of course. if not f is None and callable( f ): f( a, b )