Advertisement
rfmonk

functools_partial.py

Jan 15th, 2014
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import functools
  5.  
  6.  
  7. def myfunc(a, b=2):
  8.     """Docstring for myfunc()."""
  9.     print ' called myfunc with:', (a, b)
  10.     return
  11.  
  12.  
  13. def show_details(name, f, is_partial=False):
  14.     """Show details of a callable object."""
  15.     print '%s:' % name
  16.     print ' object:', f
  17.     if not is_partial:
  18.         print ' __name__:', f.__name__
  19.     if is_partial:
  20.         print ' func:', f.func
  21.         print ' args:', f.args
  22.         print ' keywords:', f.keywords
  23.     return
  24.  
  25. show_details('myfunc', myfunc)
  26. myfunc('a', 3)
  27. print
  28.  
  29. # Set a different default value for 'b', but require
  30. # the caller to provide 'a'.
  31. p1 = functools.partial(myfunc, b=4)
  32. show_details('partial with named default', p1, True)
  33. p1('passing a')
  34. p1('override b', b=5)
  35. print
  36.  
  37. # Set default values for both 'a' and 'b'.
  38. p2 = functools.partial(myfunc, 'default a', b=99)
  39. show_details('partial with defaults', p2, True)
  40. p2()
  41. p2(b='override b')
  42. print
  43.  
  44. print 'Insufficient arguments:'
  45. p1()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement