2018年12月24日 星期一

[ Python 常見問題 ] Currying decorator in python

Source From Here 
Question 
I am trying to write a currying decorator as @curry in python so the function can be: 
  1. @curry  
  2. def myfun(a,b,c):  
  3.     print("{}-{}-{}".format(a,b,c))  
  4.       
  5. myfun(123)  
  6. myfun(12)(3)  
  7. myfun(1)(2)(3)   
How-To 
If you are using Python2: 
  1. def curry(x, argc=None):  
  2.     if argc is None:  
  3.         argc = x.func_code.co_argcount  
  4.     def p(*a):  
  5.         if len(a) == argc:  
  6.             return x(*a)  
  7.         def q(*b):  
  8.             return x(*(a + b))  
  9.         return curry(q, argc - len(a))  
  10.     return p  
  11.   
  12. @curry  
  13. def myfun(a,b,c):  
  14.     print '%d-%d-%d' % (a,b,c)  
In Python3: 
  1. from inspect import signature  
  2.   
  3. def curry(x, argc=None):  
  4.     if argc is None:  
  5.         argc = len(signature(x).parameters)  
  6.           
  7.     def p(*a):  
  8.         if len(a) == argc:  
  9.             return x(*a)  
  10.         def q(*b):  
  11.             return x(*(a + b))  
  12.         return curry(q, argc - len(a))  
  13.     return p  
  14.   
  15. @curry  
  16. def myfun(a,b,c):  
  17.     print("{}-{}-{}".format(a,b,c))  
  18.       
  19. myfun(123)  
  20. myfun(12)(3)  
  21. myfun(1)(2)(3)  
Output: 
1-2-3
1-2-3
1-2-3

Supplement 
How can I find the number of arguments of a Python function?

沒有留言:

張貼留言

[LeetCode] Medium - 227. Basic Calculator II (G,M,A,F)

Source From  Here Question Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-nega...