A function composition operator in Python

后端 未结 3 1085
孤独总比滥情好
孤独总比滥情好 2021-01-21 03:27

In this question I asked about a function composition operator in Python. @Philip Tzou offered the following code, which does the job.

import functools

class Co         


        
3条回答
  •  借酒劲吻你
    2021-01-21 03:37

    You can step around the limitation of defining composable functions exclusively in the global scope by using the inspect module. Note that this is about as far from Pythonic as you can get, and that using inspect will make your code that much harder to trace and debug. The idea is to use inspect.stack() to get the namespace from the calling context, and lookup the variable name there.

    import functools
    import inspect
    
    class Composable:
    
        def __init__(self, func):
            self._func = func
            functools.update_wrapper(self, func)
    
        def __getattr__(self, othername):
            stack = inspect.stack()[1][0]
            other = stack.f_locals[othername]
            return Composable(lambda *args, **kw: self._func(other._func(*args, **kw)))
    
        def __call__(self, *args, **kw):
            return self._func(*args, **kw)
    

    Note that I changed func to _func to half-prevent collisions should you compose with a function actually named func. Additionally, I wrap your lambda in a Composable(...), so that it itself may be composed.

    Demonstration that it works outside of the global scope:

    def main():
        @Composable
        def add1(x):
            return x + 1
    
        @Composable
        def add2(x):
            return x + 2
    
        print((add1.add2)(5))
    
    main()
    # 8
    

    This gives you the implicit benefit of being able to pass functions as arguments, without worrying about resolving the variable name to the actual function's name in the global scope. Example:

    @Composable
    def inc(x):
        return x + 1
    
    def repeat(func, count):
        result = func
        for i in range(count-1):
            result = result.func
        return result
        
    print(repeat(inc, 6)(5))
    # 11
    

提交回复
热议问题