How can I pass all the parameters to a decorator?

I tried to trace the execution of some methods using a decorator. Here is the decorator code:

def trace(func):
    def ofunc(*args):
        func_name = func.__name__       
        xargs = args        
        print "entering %s with args %s" % (func_name,xargs)
        ret_val = func(args)
        print "return value %s" % ret_val
        print "exiting %s" % (func_name)
    return ofunc 

The thing is, if I try to apply this decorator to methods, the self parameter doesn't get sent. Can you tell me why, and how can I fix that?


Asked by: Walter323 | Posted: 30-11-2021






Answer 1

This line is incorrect:

ret_val = func(args)

You're forgetting to expand the argument list when you're passing it on. It should be:

ret_val = func(*args)

Sample output with this modification in place:

>>> class Test2:
...     @trace
...     def test3(self, a, b):
...        pass
... 
>>> t = Test2()
>>> t.test3(1,2)
entering test3 with args (<__main__.Test2 instance at 0x7ff2b42c>, 1, 2)
return value None
exiting test3
>>> 

If you ever expand your decorator to also take keyword arguments, you'd also need to expand those appropriately when passing them on, using **.

Answered by: Stuart239 | Posted: 01-01-2022



Similar questions

python - How to create a decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirectin...


python - Pass Flask route parameters into a decorator

I have written a decorator that attempts to check we have post data for a Flask POST route: Here's my decorator: def require_post_data(required_fields=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): for required_field in required_fields: if not request.form.get(required_field, None): return jsonify({"erro...


parameters - Python Fabric custom decorator

I am writing several task using Fabric 1.8 Since most of them are really similar, I wanted to do the following: # Decorator for installation task def install_task(test_task): def impl(install): def wrapper(*args, **kwargs): if not test_task(): install() return test_task() return wrapper return impl # Decorator for test task def test_ta...


Python decorator to check for POST parameters on Django

I have code that read like this to check if POST parameters are included on the request: def login(request): required_params = frozenset(('email', 'password')) if required_params &lt;= frozenset(request.POST): # 'email' and 'password' are included in the POST request # continue as normal pass else: return HttpResponseBadRequest() When the list of...


python - Decorator with parameters

Can you explain me how the following decorator works: def set_ev_cls(ev_cls, dispatchers=None): def _set_ev_cls_dec(handler): if 'callers' not in dir(handler): handler.callers = {} for e in _listify(ev_cls): handler.callers[e] = _Caller(_listify(dispatchers), e.__module__) return handler return _set_ev_cls_dec @set_ev_cls(ofp_event.EventOFPSwitchFeat...


python - Flask pass POST parameters to custom decorator

I've seen the posts on passing GET parameters and hardcoded parameters here and here. What I am trying to do is pass POST parameters to a custom decorator. The route is ...


python - Decorator taking a class and different parameters in input

This question already has answers here:


Python decorator parameters

I am familiarising with python decorators, and wondering about a general cases. Let's say I have a function to generate a person: def GeneratePerson(name, surname): return {"name": name, "surname": surname} Now, let's say I wanted a decorator to add an age: def WithAge(fn): def AddAge(*args): person = fn(args[0], args[1]) person[age] = args[2...


python - Test decorator parameters

I have a decorator that accept two parameters callback and onerror, both should be callables something like this class mydecorator(object): def __init__(self, callback, onerror=None): if callable(callback): self.callback = callback else: raise TypeError('Callable expected in "callback" parameter') self.onerror = onerror i...


python - Class decorator with parameters

MyClass = (decorator(params))(MyClass) I don't understand what this code means, since a decorator would return a function then MyClass would become a function? That sounds weird, isn't MyClass supposed to stay a class? EDIT: def decorator(name, validate, doc=None): def dec(Class): privateName = &quot;__&quot; + name def getter(self): ...


python decorator how to add parameters

This question already has answers here:


python - How to create a decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirectin...


python - How to build a decorator with optional parameters?

This question already has answers here:


python - Pass parameters to a decorator for a class method is to be decorated

I am trying to define a decorator in flask which will finally be decorating class methods passing parameters of that class instance. Here is an example what I really want to do. from functools import wraps def user_permission(myname): def decorator(f): @wraps(f) def decorated(*args,**argws): if myname == 'My Name': return f(*args,**argws) else: ...


python - change the decorator parameters when running the function?

I wrote a decorator factory that takes input and output filenames: def run_predicate(source, target): '''This is a decorator factory used to test whether the target file is older than the source file .''' import os def decorator(func): '''This is a decorator that does the real work to check the file ages.''' def wrapper(*args, **kwargs): '''Run the function if tar...


python - How to call specific function based on parameters to decorator

disclaimer: I'm obviously quite new to decorators To create and decorate functions in python is quite simple and straight forward, and this excellent answer (the one with the most upvotes), gives a very good introduction and shows how to nest decorators. Well all this is fi...


python - Pass Flask route parameters into a decorator

I have written a decorator that attempts to check we have post data for a Flask POST route: Here's my decorator: def require_post_data(required_fields=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): for required_field in required_fields: if not request.form.get(required_field, None): return jsonify({"erro...


closures - How parameters pass in decorator of python?

def require(role): def wrapper(fn): def new_fn(*args, **kwargs): if not role in kwargs.get('roles', []): print("%s not in %s" % (role, kwargs.get('roles', []))) raise Exception("Unauthorized") return fn(*args, **kwargs) return new_fn return wrapper @require('admin') def get_users(**kwargs): return ('Alice', 'Bob')


parameters - Python Fabric custom decorator

I am writing several task using Fabric 1.8 Since most of them are really similar, I wanted to do the following: # Decorator for installation task def install_task(test_task): def impl(install): def wrapper(*args, **kwargs): if not test_task(): install() return test_task() return wrapper return impl # Decorator for test task def test_ta...


Python decorator to check for POST parameters on Django

I have code that read like this to check if POST parameters are included on the request: def login(request): required_params = frozenset(('email', 'password')) if required_params &lt;= frozenset(request.POST): # 'email' and 'password' are included in the POST request # continue as normal pass else: return HttpResponseBadRequest() When the list of...


Alter default parameters of a function in a decorator in Python

I have a decorator to alter string arguments passed to functions: def decorator(fn): def wrapper(*args): replacements = list() for arg in args: new_item = arg + "!!!" replacements.append(new_item) args = tuple(replacements) print fn(*args) return wrapper I have a very simple function with a default parameter that I would like ...


python - Django: Arbitrary number of unnamed urls.py parameters

I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: /browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... where 'name' maps to a model attribute and 'value' is the search criteria for that...


python - variables as parameters in field options

I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this: home = models.ForeignKey(Team, editable=lambda self: True if self.id else False) But it doesn't work. Maybe something with overriding the init can help me, but i don't sure what can do the trick. I know i can check for self.id...


c# - How to analyse .exe parameters inside the program?

I have a program that can have a lot of parameters (we have over +30 differents options). Example: myProgram.exe -t alpha 1 -prod 1 2 -sleep 200 This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection ...


python - Default parameters to actions with Django

Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django? urlpatterns = patterns('',(r'^test/(?P&lt;name&gt;.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving...


python - Loop function parameters for sanity check

I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to ...


parameters - Python Newbie: Returning Multiple Int/String Results in Python

I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at leas...


Print out list of function parameters in Python

Is there a way to print out a function's parameter list? For example: def func(a, b, c): pass print_func_parametes(func) Which will produce something like: ["a", "b", "c"]


python - How to create a decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirectin...


python - Scope of lambda functions and their parameters?

This question already has answers here:


sql - How do you make the Python Msqldb module use ? in stead of %s for query parameters?

MySqlDb is a fantastic Python module -- but one part is incredibly annoying. Query parameters look like this cursor.execute("select * from Books where isbn=%s", (isbn,)) whereas everywhere else in the known universe (oracle, sqlserver, access, sybase...) they look like this cursor.execute("select * from Books where isbn=?", (isbn,)) This means that if you ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top