Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Decorators

Decorator which accepts an argument

How can I make a decorator that takes an argument? Suppose I want a function to repeat as many times as I want by using a decorator .as example @decorator(argument)

2 Answers

Steven Parker
Steven Parker
231,269 Points

A decorator that has parameter(s) must return a function which takes a function argument and returns another function that calls it. So essentially, it has to return a regular decorator:

def decorator(argument):
    def middle(func):               # this would be a typical decorator by itself
        def inner(*args, **kwargs):
            func(*args, **kwargs)
        return inner
    return middle

If your head hasn't exploded yet, you might investigate callable objects and partials, which can give you more elegant ways of doing this kind of thing.

Thank you for the quick reply.