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)
1 Odpowiedź
+ 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 <f> will use default value `None`
main( 1, 2 ) # None will be used as <f> argument
When parameter <f> uses default value `None`, then it is not safe to call it like so
f( a, b )
Because <f> contains a non invocable object (None).
Only when <f> contains invocable object (e.g. function reference) the referenced function will be invoked, passing <a> and <b> arguments.
To be safer, you can add a condition to verify whether <f> refers an invocable object. This ensures that argument <f> 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 )