''' closures.py closures are functions defined inside another function The outer function returns a pointer to the inner function. This is not your average everyday darkness. This is advanced darkness ''' def print_hello(name): def printx(x): str="" for _ in range(x): str += ("hello " + name + "\t") return str return printx printSponge = print_hello('Spongebob') printPat = print_hello('Patrick') print(printSponge(5)) print(printPat(7)) ''' decorators are function closures that "decorate" a third function, defined outside the closure. The decorator is a closure where the outer function takes a function pointer to the third function as a parameter and returns a pointer to the inner function. The inner function takes the same set of parameters as the third function and involves a call to the third function with some added functionality. ''' # Here, p_decorate is a decoratoe for answer_phone def answer_phone(name): return "No, this is " + str(name) def p_decorate(func): def func_wrap(name): return "
" + func(name) + "
" return func_wrap atPhone = p_decorate(answer_phone) print(atPhone("Patrick")) print(atPhone("Squidward")) ''' The above is the standard syntax and is used when we want to keep the old function with the old functionality. Python also provides us with an easier syntax, shown below, when we want to call the old function name, but want the new functionality executed. ''' @p_decorate def ask(name): return "Is this " + str(name) +"?" print(ask("the Krusty Krab"))