Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Registering Plugins With Decorators

In this lesson, you’ll learn how to create a simple plugin architecture using decorators.

Comments & Discussion

Sam W on May 31, 2020

I think I’ve missed something already explained. I wanted to ask about the different form of decorator here. Why does it not have include the inside wrapper function?

And now I’m wondering why we can’t do similar to the above all the time.

e.g.

Why can’t a decorator from before, such as:

def slow_down(func):
    """ Delay for 1 second """
    def wrapper_slow_down_one():
        time.sleep(1)
        return func()
    return wrapper_slow_down_one

not instead just be:

def slow_down(func):
    """ Delay for 1 second """
    time.sleep(1)
    return func

Geir Arne Hjelle RP Team on May 31, 2020

Hi Sam,

the different pattern used here for @register can be used when your decorator only needs to do something when the decorated function is defined, in this case it’s registered to a dictionary.

Since we’re not changing the function that has been passed in, that function will work exactly as if it had not been decorated. In the usual pattern, the decorated function is instead replaced by the inner wrapper function.

If you use your simplified @slow_down decorator, you will notice that the code sleeps for 1 second whenever you define a new decorated function, but it will not sleep when you call that decorated function.

Sam W on June 1, 2020

Oh of course. Seems obvious now you say it. Ok, thank you.

Become a Member to join the conversation.