CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Functions Redux (part 2)


  1. Variable length args (*args)
  2. Keyword args (**kwargs)
  3. Functions that return functions
  4. Function decorators

  1. Variable length args (*args)
    def longestWord(*args): if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print(longestWord("this", "is", "really", "nice")) # really mywords = ["this", "is", "really", "nice"] print(longestWord(mywords)) # ['this', 'is', 'really', 'nice'] print(longestWord(*mywords)) # really

  2. Keyword args (**kwargs)
    def f(x=1, y=2): return (x,y) print(f()) # (1, 2) print(f(3)) # (3, 2) print(f(y=3)) # (1, 3) [here is where we use a keyword arg] def f(x, **kwargs): return (x, kwargs) print(f(1)) # (1, { }) print(f(2, y=3, z=4)) # (2, {'z': 4, 'y': 3})

  3. Functions that return functions
    def derivativeFn(f): def g(x): h = 10**-5 return (f(x+h) - f(x))/h return g def f(x): return 5*x**3 + 10 fprime1 = derivativeFn(f) fprime2 = derivativeFn(fprime1) print(f(3)) # 145, 5*x**3 + 10 evaluated at x == 3 print(fprime1(3)) # about 135, 15*x**2 evaluated at x == 3 print(fprime2(3)) # about 90, 30*x evaluated at x == 3

  4. Function decorators
    @derivativeFn def h(x): return 5*x**3 + 10 print(h(3)) # 135, matches fprime1 from above.