How to write a decorator to wrap something in a context manager that accepts parameters?

I saw How to use the context manager inside the decorator and how to pass the object created in the decorator to the decorated function , as well as python decorators with parameters , and I'm trying to combine the two ... but I'm struggling to get around it.

I would rather use the func tools @wrap tools to do this, if possible, since I know if the doc string will save.

I want to do the following:

 def pyro_opener(func,service,database,port,secret_key): def wrapper(params): with Pyro4.Proxy("PYRO:"+service+"@"+database+":"+port) as obj: obj.set_secret_key(secret_key) return obj.func(params) return wrapper @pyro_opener(output_service, employee_db,port=9876,secret_key="h3llow0rld") def get_employee_names(salary): return obj.return_employee_names(salary) # obj is clearly not in scope here # but what else can I do? get_employee_names(25000) >>>> Bob, Jane, Mary 

I do not think this works like this, the return_employee_names method is on the service at the other end of the connection. Should I just return a function call? If so, how do I pass the parameters to ??

+8
python decorator python-decorators pyro
source share
1 answer

You will pass the object associated with with ... as with the completed function; the function should accept such an argument.

This is similar to how the methods work; they are just functions with an optional first argument ( self ) passed to:

 def pyro_opener(service, database, port, secret_key): def decorator(func): @wraps(func) def wrapper(*args, **kw): with Pyro4.Proxy("PYRO:{}@{}:{}".format(service, database, port)) as obj: obj.set_secret_key(secret_key) return func(obj, *args, **kw) return wrapper retutrn decorator @pyro_opener(output_service, employee_db, port=9876, secret_key="h3llow0rld") def get_employee_names(obj, salary): return obj.return_employee_names(salary) 

Note that I had to add another nested function to pyro_opener() to make it a suitable factory decorator.

+6
source share

All Articles