Build a Plugin System with Protocols
Advanced · Write the code · from Python Protocols: Duck Typing with Type Safety
From the lesson: Python Protocols: Duck Typing with Type Safety
Python has a famous saying: "If it walks like a duck and quacks like a duck, then it's a duck." This is called duck typing - you don't care what an object is, only what it can do. But duck typing has a downside: your editor and type checker have no idea what you expect.
Read the lessonBuild a simple plugin system using Protocols.
1. Define a Plugin Protocol with two methods:
- name() -> str
- execute(data: str) -> str
2. Create an UpperPlugin class where name() returns "upper" and execute(data) returns data.upper().
3. Create a ReversePlugin class where name() returns "reverse" and execute(data) returns data[::-1].
4. Write a function run_plugins(plugins, data) that takes a list of plugins and a string. For each plugin, print "{plugin.name()}: {plugin.execute(data)}".
5. Call run_plugins with both plugins and the string "hello".
More Protocol exercises
All Python exercises · 50 practice problems · Advanced Python quiz