Files
  • main.py
main.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
  A mock-up for freenode #python of a decorator factory that tests predicates before calling the wrapped
  function AND passes the value along to the function to be re-used.
"""

def decfact(preddict):
  def dec(wrapped, *args, **kwargs):
    def g(*args, **kwargs):
      predvals = {predkey:predfunc(*args, **kwargs) for predkey,predfunc in preddict.items()}
      if all(predvals.values()):
        return wrapped(*args, **predvals, **kwargs)
      else:
        raise ValueError(f'Predicate failed for {wrapped.__name__}()')
    g.pred = preddict
    return g
  return dec

def truepred(*args):
  return True

def falsepred(*args):
  return False

@decfact({'pred': truepred})
def foo(x, y, pred):
  print(pred)
  return x + y

@decfact({'pred': falsepred})
def bar(x, y, pred):
  print(pred)
  return x + y

print(foo.pred)
print(bar.pred)

foo(1, 2)
bar(1, 2)