Sitemap
Tushar

Tushar

Software Engineer at TTN

Protocols in Python

2 min readNov 30, 2022

If you have heard about the Abstract classes, you will be a quick grabber.

Protocols are the best way to make the methods, functions, or classes follow a set of rules (introduced in the 3.8 version of python).

In other words, Protocols are used to structure the sub-types/annotates/derives

Protocol class can be imported from python’s standard module named typing

Let’s define a basic Protocol to be used for structuring a sub-type

Press enter or click to view image in full size

Tools is an enumerate class to hold the possible constants that can be provided as an argument to burn or smash method

Get Tushar’s stories in your inbox

Join Medium for free to get updates from this writer.

Kill is a Protocol class that will tell its annotated/derived function/class to provide an object which should have smash and burn.

Press enter or click to view image in full size

Now every call to the kill_mosquito function suggests providing an object which follows the Protocol defined rules.

Conclusion

Protocols help in writing scalable and understandable code, as the code becomes lengthy it becomes challenging to understand.

Protocols will be proved as heroes in those kinds of situations.

Further related articles

Interface using zope, Abstract Classes

Official Website https://pythonbricks.pythonanywhere.com/

Youtube Channel https://www.youtube.com/@PythonBricks

Telegram https://t.me/pythonbricks

--

--