This lesson is from the Real Python video course by Christopher Bailey.
Registering Plugins With Decorators
00:01
In this last example, I’ll show you how you can register functions using a decorator, sort of like registering plugins. For this final example, I’m going to have you work just inside the REPL. Start by importing random
.
00:16
You’ll see why in a moment and how you’re going to use it. Make a dictionary named PLUGINS
. Make a decorator. Its name is register()
.
00:28
It’s going to look very different from the ones that you’ve made up to this point—a little simpler. It will have a docstring saying that it’s designed to """Register a function as a plug-in"""
.
00:39
Using PLUGINS
, take that func
that comes in—”Yeah, that funk that comes in”—and using the .__name__
method, add it to functions.
00:52
Then, return the function unchanged. Great. There’s register()
.
01:00
Now use that as a decorator as you define… These are functions that you created a long time ago. say_hello()
takes a name
as an argument and returns an f-string, with a very simple f"Hello "
, and name
as the expression.
01:19
There’s say_hello()
. And register this one also. It’s called be_awesome()
. It takes a name
as an argument and this time returns an f-string with the expression name
in it.
01:40
All right. What’s inside PLUGINS
now? PLUGINS
now has two functions inside of it as the dictionary: say_hello
and be_awesome
. Pretty cool! Well, how are you going to use it? Next, you’re going to make a function called randomly_greet()
.
01:59
It takes a name
as an argument.
02:05
A greeter and a greeter function—here’s where we’re using random
. With the method choice()
it’s going to pull out of PLUGINS
—we’ll make it into an iterator by using the method .items()
. Close off all those parentheses.
02:21
So, random.choice()
out of the PLUGINS
dictionary to populate greeter
and greeter_func
. Using print()
, make an f-string saying f"Using "
which greeter
in its repr()
version. Close off the print statement. And then return with a call to that greeter()
function, with the name
that has been passed in. All right!
02:48
I’ll make some space. Now, randomly_greet()
is available and let’s say you want to greet "Alice"
. So here, it’s saying that it’s using the greeter function 'be_awesome'
, so it randomly picked that one. Try it again. Now it used 'say_hello'
.
03:07 Pretty neat! So you could have multiple functions that you’re registering in to create this simplified plugin architecture.
03:17 The main benefit of this simple architecture is that you don’t actually have to maintain a list of which plugins exist. The list gets created every time you register a plugin by applying the decorator to any of those functions, which is pretty neat! Okay.
03:33 It’s time to wrap up Decorators 101 with a final review.
You must own this product to join the conversation.