0

As part of improving the syntax for Aspect-Oriented Programming in Python based on the excellent answer by jsbueno: Aspect oriented programming (AOP) in Python , I was wondering if it's possible to accept a function template as a parameter in Python with any decoration.

Eg, being able to call foo(bar(5)) with bar undefined, and have foo receive an object representing the expression bar(5); rather than an error that bar is undefined. (This would then be used as an input to construct a rule for matching incoming network messages indicating that another node has run function bar with parameter 5.)

Is there any better way to do this than passing the template as a string and parsing it with ast?

Mark Green
  • 1,310
  • 12
  • 19
  • What do you want to achieve? What will function `foo()` do when `bar` is undefined? – Andrej Kesely Jun 26 '19 at 18:42
  • 1
    Not sure if this is what you're looking for without knowing more context, but couldn't you just accept `bar` as a parameter to the enclosing function, then pass in whatever function you want to be used? – Carcigenicate Jun 26 '19 at 18:43
  • This sounds like a bad idea to me. With a syntax like that, you have to always be aware of which functions actually exist (like `foo`) and which are pseudo-functions (like `bar`). If you later define a `bar` method, suddenly your old code might stop working - or at the very least it'll be ambiguous. It might look convenient now, but when you actually have to use it... – Aran-Fey Jun 26 '19 at 18:51
  • I wouldn't mind if there was some annotation to apply to the syntax to indicate this (but ideally not just making it a string) – Mark Green Jun 26 '19 at 18:56

1 Answers1

0

I am not exactly sure, what your looking for, maybe this will help:

def decorator(f):
    def wrapper(*args, **kwargs):
        print("f in wraper with: {}".format(f.__defaults__))
        return f(*args, **kwargs)
    return wrapper

funcs = {}
fdefaults = [1, 2, 3]
code = """def myfunc(x={}): return print("f returning:", *x)""".format(fdefaults)

exec(code, {}, funcs)
myfunc = decorator(funcs["myfunc"])
myfunc()

outputs: f in wraper with: ([1, 2, 3],) f returning: 1 2 3

lmielke
  • 135
  • 8