Welcome, guest | Sign In | My Account | Store | Cart

Decorator for the "f . g" style of function composition familiar to functional programmers.

Python, 25 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class CF(object):
    'Decorator for creating a composable function'

    def __init__(self, f):
        self.func = f

    def __call__(self, x):
        return self.func(x)
       
    def __getattr__(self, other):
        other = globals()[other]
        return CF(lambda x: self(other(x)))


#-------- Example ----------

@CF
def f(x):
    return 3 * x

@CF
def g(x):
    return x + 10

print (f . g)(2)    # same as f(g(2))
Created by Raymond Hettinger on Sat, 12 Jul 2008 (PSF)
Python recipes (4591)
Raymond Hettinger's recipes (97)

Required Modules

  • (none specified)

Other Information and Tasks