The decorator login_required is passed the function (hello in this case).

So what you want to do is:

def login_required(f):
    # This function is what we "replace" hello with
    def wrapper(*args, **kw):
        args[0].client_session['test'] = True
        logged_in = 0
        if logged_in:
            return f(*args, **kw)  # Call hello
        else:
            return redirect(url_for('login'))
    return wrapper
Answer from brian-brazil on Stack Overflow
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › the-ultimate-guide-to-python-decorators-part-iii-decorators-with-arguments
The Ultimate Guide to Python Decorators, Part III: Decorators with Arguments - miguelgrinberg.com
Here you can see that my_decorator takes no arguments when it is used to decorate a function, but the implementation of this decorator does take the f argument, through which Python passes a reference to the decorated function.
Discussions

python - access function arguments from function decorator - Stack Overflow
If I have a function that looks like: @app.route('/categories/id/ /edit') @login_required def edit_category(id): #some code... And the login_required decorator looks like this def More on stackoverflow.com
🌐 stackoverflow.com
How to access inner functions parameters using a Decorator?
That is not only possible, it's really the whole point of decorators: you wrap the original function, either doing something with its parameters before calling it, or with its result after calling it. But this all needs to be done in the wrapper, not the decorator. So: def log_filtered_rows(func): def wrapper(*args, **kwargs): # do something with args or kwargs result = func(*args, **kwargs) # do something with result return result return wrapper More on reddit.com
🌐 r/learnpython
7
1
March 31, 2023
python - Accessing function arguments from decorator - Stack Overflow
Try this approach: Can a Python decorator of an instance method access the class? Not the exact same question but you should be able to use the same approach to create a reference to self or a reference to a dictionary with objects of a certain class in it that you can get out in your decorator. ... Save this answer. ... Show activity on this post. Copyimport random #decorator to the get function ... More on stackoverflow.com
🌐 stackoverflow.com
Decorators get the decorated args?
Hi, in def f1(aFunc): def DecoratedWrapper(*args,**kwargs): print(kwargs) val = aFunc(*args,**kwargs) print('Finished','\n') return val return DecoratedWrapper @f1 def f(a,b=9): print(a,b) @f1 def add(x,y): return x + y f('Hello') print(add(5,3)) The line 3 print(kwargs) print nothing !? who ... More on discuss.python.org
🌐 discuss.python.org
6
0
June 12, 2024
🌐
Fabian Lee
fabianlee.org › 2019 › 09 › 22 › python-using-a-custom-decorator-to-inspect-function-arguments
Python: Using a custom decorator to inspect function arguments | Fabian Lee : Software Engineer
September 23, 2019 - # custom decorator def ... # matches name of inner function return wrapper · It uses the variable positional and keyword arguments (*args,**kwargs) so that it can decorate a function with any number of ...
🌐
Reddit
reddit.com › r/learnpython › how to access inner functions parameters using a decorator?
r/learnpython on Reddit: How to access inner functions parameters using a Decorator?
March 31, 2023 -

Basically I have multiple functions in a library which take in pandas Dataframe objects and perform operations on them. These include merges, or filtering.

I want to log the rows that are being filtered out due to these functions.

Every dataset has a unique identifier like an index and so I want to log the index number.

I was thinking of using a decorator for this, something like below.

Essentially what I want to do in the decorator is:

# func is the function that will be doing the merges or filters.
def log_filtered_rows(func):
    # Take func's parameter - the dataframe that will be passed to it. 
    # run func 
    # compare the initial dataframe with the one that func returned and log the rows             that are missing.

Any help on this would be appreciated. I am new to using decorators and not sure this is even possible but if there is another way, then let me know.

Top answer
1 of 5
11

I'm not entirely clear what it is you want, but if you just want to use the decorated function's arguments, then that is exactly what a basic decorator does. So to access say, self.request from a decorator you could do:

def log_request(fn):
    def decorated_get(self):
        logging.debug("request object:", self.request)
        return fn(self)
    return decorated_get

class MyHandler(webapp. RequestHandler):
    @log_request
    def get(self):
        self.response.out.write('hello world')

If you are trying to access the class the decorated function is attached to, then it's a bit tricker and you'll have to cheat a bit using the inspect module.

import inspect

def class_printer(fn):
    cls = inspect.getouterframes(inspect.currentframe())[1][3]
    def decorated_fn(self, msg):
        fn(self,cls+" says: "+msg)
    return decorated_fn

class MyClass():
    @class_printer
    def say(self, msg):
        print msg

In the example above we fetch the name of the class from the currentframe (during the execution of the decorator) and then store that in the decorated function. Here we are just prepending the class-name to whatever the msg variable is before passing it on to the original say function, but you can use your imagination to do what ever you like once you have the class name.

>>> MyClass().say('hello')
MyClass says: hello
2 of 5
2

source

def p_decorate(func):
   def func_wrapper(name):
       return "<p>{0}</p>".format(func(name))
   return func_wrapper

@p_decorate
def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

print get_text("John")

# Outputs <p>lorem ipsum, John dolor sit amet</p>
🌐
DEV Community
dev.to › apcelent › python-decorator-tutorial-with-example-529f
Python Decorator with Arguments: Python Decorator Tutorial with Example - DEV Community
July 30, 2018 - class ClassDecorator(object): def __init__(self, arg1, arg2): print "Arguements passed to decorator %s and %s" % (arg1, arg2) self.arg1 = arg1 self.arg2 = arg2 def __call__(self, foo, *args, **kwargs): def inner_func(*args, **kwargs): print "Args passed inside decorated function .%s and %s" % (self.arg1, self.arg2) return foo(*args, **kwargs) return inner_func @ClassDecorator("arg1", "arg2") def print_args(*args): for arg in args: print arg print_args(1, 2, 3) Arguements passed to decorator arg1 and arg2 Args passed inside decorated function .arg1 and arg2 1 2 3 · How would you go about implementing decorator with optional arguments?
🌐
Real Python
realpython.com › primer-on-python-decorators
Primer on Python Decorators – Real Python
September 1, 2026 - Python decorators allow you to ... you use a Python decorator, you wrap a function with another function, which takes the original function as an argument and returns its modified version....
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › decorators-with-parameters-in-python
Decorators with parameters in Python - GeeksforGeeks
August 27, 2024 - In Python, decorators are a powerful ... their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality....
🌐
Quora
quora.com › In-python-How-do-I-implement-a-function-decorator-which-prints-the-arguments-and-result-of-wrapped-functions
In python, How do I implement a function decorator which prints the arguments and result of wrapped functions? - Quora
Answer: This sort of thing is relatively simple. Remember that a decorator needs to return a function that does the same as the function being decorated, but with the extra functionality. Remember that when we do: [code]@decorator def add(a,b): “””Returns the sum of two numbers””” ...
🌐
Python.org
discuss.python.org › python help
Decorators get the decorated args? - Python Help - Discussions on Python.org
June 12, 2024 - Hi, in def f1(aFunc): def DecoratedWrapper(*args,**kwargs): print(kwargs) val = aFunc(*args,**kwargs) print('Finished','\n') return val return DecoratedWrapper @f1 def f(a,b=9): print(a,b) @f1 def add(x,y…
🌐
Python Tutorial
pythontutorial.net › home › advanced python › python decorator with arguments
Python Decorator with Arguments
March 27, 2025 - from functools import wraps def repeat(fn): @wraps(fn) def wrapper(*args, **kwargs): for _ in range(5): result = fn(*args, **kwargs) return result return wrapper @repeat def say(message): ''' print the message Arguments message: the message to show ''' print(message) say('Hello')Code language: Python (python) ... What if you want to execute the say() function repeatedly ten times. In this case, you need to change the hard-coded value 5 in the repeat decorator.
Top answer
1 of 16
1289

The syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is:

def decorator_factory(argument):
    def decorator(function):
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            result = function(*args, **kwargs)
            more_funny_stuff()
            return result
        return wrapper
    return decorator

Here you can read more on the subject - it's also possible to implement this using callable objects and that is also explained there.

Usage:

@decorator_factory("Some argument")
def function_to_be_decorated(args):
    print(f"Do something with '{args}'.")

decorator_factory("Some argument") uses the given argument to create a standard, argumentless decorator. So the following block is functionally identical to the one above:

created_decorator = decorator_factory("Some argument")

@created_decorator
def function_to_be_decorated(args):
    print(f"Do something with '{args}'.")
2 of 16
559

Edit : for an in-depth understanding of the mental model of decorators, take a look at this awesome Pycon Talk. well worth the 30 minutes.

One way of thinking about decorators with arguments is

@decorator
def foo(*args, **kwargs):
    pass

translates to

foo = decorator(foo)

So if the decorator had arguments,

@decorator_with_args(arg)
def foo(*args, **kwargs):
    pass

translates to

foo = decorator_with_args(arg)(foo)

decorator_with_args is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function).

I use a simple trick with partials to make my decorators easy

from functools import partial

def _pseudo_decor(fun, argument):
    def ret_fun(*args, **kwargs):
        #do stuff here, for eg.
        print ("decorator arg is %s" % str(argument))
        return fun(*args, **kwargs)
    return ret_fun

real_decorator = partial(_pseudo_decor, argument=arg)

@real_decorator
def foo(*args, **kwargs):
    pass

Update:

Above, foo becomes real_decorator(foo)

One effect of decorating a function is that the name foo is overridden upon decorator declaration. foo is "overridden" by whatever is returned by real_decorator. In this case, a new function object.

All of foo's metadata is overridden, notably docstring and function name.

>>> print(foo)
<function _pseudo_decor.<locals>.ret_fun at 0x10666a2f0>

functools.wraps gives us a convenient method to "lift" the docstring and name to the returned function.

from functools import partial, wraps

def _pseudo_decor(fun, argument):
    # magic sauce to lift the name and doc of the function
    @wraps(fun)
    def ret_fun(*args, **kwargs):
        # pre function execution stuff here, for eg.
        print("decorator argument is %s" % str(argument))
        returned_value =  fun(*args, **kwargs)
        # post execution stuff here, for eg.
        print("returned value is %s" % returned_value)
        return returned_value

    return ret_fun

real_decorator1 = partial(_pseudo_decor, argument="some_arg")
real_decorator2 = partial(_pseudo_decor, argument="some_other_arg")

@real_decorator1
def bar(*args, **kwargs):
    pass

>>> print(bar)
<function __main__.bar(*args, **kwargs)>

>>> bar(1,2,3, k="v", x="z")
decorator argument is some_arg
returned value is None
🌐
SitePoint
sitepoint.com › blog › programming › understanding python decorators, with examples
Understanding Python Decorators, with Examples — SitePoint
November 6, 2024 - Real-life use cases of Python decorators include time logging, memoization, and built-in Python decorators like @classmethod, @staticmethod, and @property. In Python, functions are first-class objects, meaning they can receive arguments or be passed as arguments.
🌐
Real Python
realpython.com › lessons › decorating-functions-arguments
Decorating Functions With Arguments (Video) – Real Python
There’s a standardized way to do that. Let’s rewrite this. 03:46 You’re going to add *args and **kwargs—which stands for arguments and keyword arguments—to your decorator.
Published: March 19, 2019
Top answer
1 of 4
6

I'm not a fan of this design. @TheBlackCat is right. Don't do this.

If you are to do this, rethink your design. A more sensible one might look like

import functools
from contextlib import suppress

def try_except_response(func):
    @functools.wraps(func)
    def wrapper(*args, fail_silently, **kwargs):
        if fail_silently:
            with suppress(Exception):
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return wrapper

The key principle here is KISS.

Note that I'm suppressing Exception, not BaseException, since catching SystemExit and KeyboardInterrupt is almost always a bad idea.

If you want to make fail_silently a default argument, just use another wrapper:

def default_fail_silently(default):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, fail_silently=default, **kwargs):
            return func(*args, fail_silently=fail_silently, **kwargs)
        return wrapper
    return decorator

Then you can do

@default_fail_silently(False)
@try_except_response
def test(a, b, c=1)
    return int(a) + c

This does mean there's more boilerplate, since it exists for each piece of functionality you add, but the logic itself is an order of magnitude simpler.

2 of 4
2

Your code looks really nice, I saw a few parts that might be improved:

  1. if kwargs.get(parameter)== True:: binary operators are suggested, by PEP8, to have a space pre&proceeding the operator =
  2. function_args, vargs, kewords,: is that last one a misspell?

  3. if keyword == True:: If you're testing whether the variable is empty, as PEP8 says, you can use if keyword


Other than that, your code looks really nice, good work!

🌐
GitHub
gist.github.com › Zearin › 2f40b7b9cfc51132851a
The best explanation of Python decorators I’ve ever seen. (An archived answer from StackOverflow.)
Look:', arg1, arg2 function_to_decorate(arg1, arg2) return a_wrapper_accepting_arguments # Since when you are calling the function returned by the decorator, you are # calling the wrapper, passing arguments to the wrapper will let it pass them to # the decorated function @a_decorator_passing_arguments def print_full_name(first_name, last_name): print 'My name is', first_name, last_name print_full_name('Peter', 'Venkman') # outputs: #I got args! Look: Peter Venkman #My name is Peter Venkman · One nifty thing about Python is that methods and functions are really the same.
🌐
CodingNomads
codingnomads.com › python-decorators-with-arguments
Python Decorators With Arguments
To be able to handle arguments that you pass to your decorator, you need to go deeper to yet another level by adding another function wrapper to your decorator construct.