Python: changing the internal behavior of a function using a decorator

I am studying using python decorator.

def my_dcrtr(fun):
    def new_fun():
        return fun()
    return new_fun

I understand that the decorated fun function acts like a black box inside the decorator. I can choose to use fun () or not at all inside new_fun. However, I don't know if I can break into the “fun” and interact with an interesting local area inside new_fun?

eg. I am trying to make a game with remote procedural call (RPC) using python.

def return_locals_rpc_decorator(fun):
    def decorated_fun(*args, **kw):
        local_args = fun(*args, **kw)
        # pickle the local_args and send it to server
        # server unpickle and doing the RPC
        # fetch back server results and unpickle to results
        return rpc_results

    return decorated_fun


@return_locals_rpc_decorator
def rpc_fun(a, b, c=3):
    return locals() # This looks weird. how can I make this part of the decorator?


print(rpc_fun(2, 1, 6))

In this example, I am trying to get a list of rpc_fun arguments at runtime using the locals () command. Then send it to the server for execution. Instead of letting rpc_fun return its locals (), is it possible to use a decorator to retrieve the decorated function argument space?

+6
1

Python3:

def return_locals_rpc_decorator(fun):
   def decorated_fun(*args, **kw):
      local_args = fun(*args, **kw) 
      print(local_args)
      fun_parameters = fun.__annotations__
      final_parameters = {a:list(args)[int(b[-1])-1] for a, b in fun_parameters.items() if a != 'return'}
      return final_parameters
   return decorated_fun

@return_locals_rpc_decorator
def my_funct(a:"val1", b:"val2", c:"val3") -> int:
    return a + b + c

print(my_funct(10, 20, 30))

:

60
{'a': 10, 'b': 20, 'c': 30}

, decorated_fun , . , , args. , , .

: my_funct - (decorated_fun), args, decorated_fun, local_args.

+3
source

All Articles