Remember that calling a function and defining a function are two completely different things. The latter creates a function that can later be called and declares what parameters must be given at call time. Since there is no call to the function then, there's no checking of what parameters are declared (how could there be?). That is the same regardless of whether that definition is nested inside another function or not. Calling a function necessitates passing the right number of arguments and obviously checking against the definition only happens at call time. This happens regardless of what scope that call is in (whether inside a function or at a global level, for example).
Let's say you want to measure execution times of function calls and record those somewhere. Of course, you could just change all your functions to do that, but you'd be repeating similar code everywhere. Another approach is to write a function that takes as its argument a function
This is known as a decorator and Python has syntax to decorate functions:
Let's say you want to measure execution times of function calls and record those somewhere. Of course, you could just change all your functions to do that, but you'd be repeating similar code everywhere. Another approach is to write a function that takes as its argument a function
f
and produces a new one that calls f
and does the measurement and recording of the time:def measure_time(f): def measured(): start_time = calculate_time() result = f() end_time = calculate_time() record_time(end_time - start_time) return result return measured(I've used fictional functions and just taken the case that
f
takes no arguments, for the sake of simplicity).This is known as a decorator and Python has syntax to decorate functions:
@measure_time def do_something_useful(): ...Here, basically, with the presence of the
@measure_time
decorator, do_something_useful
will really be the function that measure_time
returns (i.e. one that does exactly the same as do_something_useful
but with the additional recording of the execution time.