In this lesson, you’ll learn how to create a simple plugin architecture using decorators.
Registering Plugins With Decorators
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
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.
All right. What’s inside
PLUGINS now has two functions inside of it as the dictionary:
be_awesome. Pretty cool! Well, how are you going to use it? Next, you’re going to make a function called
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.
random.choice() out of the
PLUGINS dictionary to populate
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!
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
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.
Become a Member to join the conversation.