code_junkie

What is the most pythonic way to make a bound method act like a function

Nov 13th, 2011
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. class A(object):
  2. def hello(self, salutation):
  3. print('%s, my name is %s' % (salutation, str(self)))
  4.  
  5. def bind_hello1(self):
  6. return lambda x: self.hello(x)
  7.  
  8. def bind_hello2(self):
  9. def hello2(*args):
  10. self.hello(*args)
  11. return hello2
  12.  
  13.  
  14. >>> a1, a2 = A(), A()
  15. >>> a1.hello('Greetings'); a2.hello('Greetings')
  16. Greetings, my name is <__main__.A object at 0x71570>
  17. Greetings, my name is <__main__.A object at 0x71590>
  18.  
  19. >>> f1, f2 = a1.bind_hello1(), a2.bind_hello1()
  20. >>> f1('Salutations'); f2('Salutations')
  21. Salutations, my name is <__main__.A object at 0x71570>
  22. Salutations, my name is <__main__.A object at 0x71590>
  23.  
  24. >>> f1, f2 = a1.bind_hello2(), a2.bind_hello2()
  25. >>> f1('Aloha'); f2('Aloha')
  26. Aloha, my name is <__main__.A object at 0x71570>
  27. Aloha, my name is <__main__.A object at 0x71590>
  28.  
  29. In [2]: class C(object):
  30. ...: def method(self, a, b, c):
  31. ...: print a, b, c
  32. ...:
  33. ...:
  34.  
  35. In [3]: def api_function(a_func):
  36. ...: a_func("One Fish", "Two Fish", "Blue Fish")
  37. ...:
  38. ...:
  39.  
  40. In [4]: c = C()
  41.  
  42. In [5]: api_function(c.method)
  43. One Fish Two Fish Blue Fish
  44.  
  45. def callback(fn):
  46. fn('Welcome')
  47. callback(a1.hello)
  48. callback(a2.hello)
  49.  
  50. class curry:
  51. def __init__(self, fun, *args, **kwargs):
  52. self.fun = fun
  53. self.pending = args[:]
  54. self.kwargs = kwargs.copy()
  55.  
  56. def __call__(self, *args, **kwargs):
  57. if kwargs and self.kwargs:
  58. kw = self.kwargs.copy()
  59. kw.update(kwargs)
  60. else:
  61. kw = kwargs or self.kwargs
  62.  
  63. return self.fun(*(self.pending + args), **kw)
  64.  
  65. f1 = curry(a1.hello, 'Salutations')
  66. f1() # == a1.hello('Salutations')
Add Comment
Please, Sign In to add comment