Python's dynamic nature and support for duck typing have long been praised for their flexibility. However, as codebases grow larger and more complex, the benefits of static type checking become increasingly apparent. But how can we reconcile the flexibility of duck typing with the safety of static type checking? Enter Python's Protocol class.
In this tutorial, you'll learn:
- What duck typing is and how it's supported in Python
- The pros and cons of duck typing
- How Abstract Base Classes (ABCs) attempt to solve typing issues
- How to use Protocol to get the best of both worlds: duck typing flexibility with static type checking
Understanding Duck Typing
Duck typing is a programming concept where the type or class of an object is less important than the methods it defines. It's based on the idea that "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."
In Python, duck typing is fully supported. For example:
class Duck: def quack(self): print("Quack!") class Person: def quack(self): print("I'm imitating a duck!") def make_it_quack(thing): # Note: No type hint here thing.quack() duck = Duck() person = Person() make_it_quack(duck) # Output: Quack! make_it_quack(person) # Output: I'm imitating a duck!
In this example, make_it_quack doesn't care about the type of thing. It only cares that thing has a quack method. Note that there's no type hint for the thing parameter, which is typical in duck-typed code but can lead to issues in larger codebases.
Pros and Cons of Duck Typing
Duck typing offers several advantages:
- Flexibility: It allows for more flexible code that isn't tied to specific types.
- Easier code reuse: You can use existing classes in new contexts without modification.
- Emphasis on behavior: It focuses on what an object can do, rather than what it is.
However, it also has some drawbacks:
- Lack of clarity: It can be unclear what methods an object needs to implement.
- Runtime errors: Type-related errors are only caught at runtime.
- Less IDE support: IDEs struggle to provide accurate autocompletion and error checking.
The ABC Solution
One approach to addressing these issues is using Abstract Base Classes (ABCs). Here's an example:
from abc import ABC, abstractmethod class Quacker(ABC): @abstractmethod def quack(self): pass class Duck(Quacker): def quack(self): print("Quack!") class Person(Quacker): def quack(self): print("I'm imitating a duck!") def make_it_quack(thing: Quacker): thing.quack() duck = Duck() person = Person() make_it_quack(duck) make_it_quack(person)
While this approach provides better type checking and clearer interfaces, it has disadvantages:
- It requires inheritance, which can lead to inflexible hierarchies.
- It doesn't work with existing classes that you can't modify.
- It goes against Python's "duck typing" philosophy.
Protocols: The Best of Both Worlds
Python 3.8 introduced the Protocol class, which allows us to define interfaces without requiring inheritance. Here's how we can use it:
from typing import Protocol class Quacker(Protocol): def quack(self):... class Duck: def quack(self): print("Quack!") class Person: def quack(self): print("I'm imitating a duck!") def make_it_quack(thing: Quacker): thing.quack() duck = Duck() person = Person() make_it_quack(duck) make_it_quack(person)
Let's break this down:
- We define a Quacker protocol that specifies the interface we expect.
- Our Duck and Person classes don't need to inherit from anything.
- We can use type hints with make_it_quack to specify that it expects a Quacker.
This approach gives us several benefits:
- Static type checking: IDEs and type checkers can catch errors before runtime.
- No inheritance required: Existing classes work as long as they have the right methods.
- Clear interfaces: The Protocol clearly defines what methods are expected.
Here's a more complex example showing how Protocols can be as complex as needed (Shape), keeping your domain classes (Circle, Rectangle) flat:
from typing import Protocol, List class Drawable(Protocol): def draw(self): ... class Resizable(Protocol): def resize(self, factor: float): ... class Shape(Drawable, Resizable, Protocol): pass def process_shapes(shapes: List[Shape]): for shape in shapes: shape.draw() shape.resize(2.0) # Example usage class Circle: def draw(self): print("Drawing a circle") def resize(self, factor: float): print(f"Resizing circle by factor {factor}") class Rectangle: def draw(self): print("Drawing a rectangle") def resize(self, factor: float): print(f"Resizing rectangle by factor {factor}") # This works with any class that has draw and resize methods, # regardless of its actual type or inheritance shapes: List[Shape] = [Circle(), Rectangle()] process_shapes(shapes)
In this example, Circle and Rectangle don't inherit from Shape or any other class. They simply implement the required methods (draw and resize). The process_shapes function can work with any objects that have these methods, thanks to the Shape protocol.
Summary
Protocols in Python provide a powerful way to bring static typing to duck-typed code. They allow us to specify interfaces in the type system without requiring inheritance, maintaining the flexibility of duck typing while adding the benefits of static type checking,
By using Protocols, you can:
- Define clear interfaces for your code
- Get better IDE, (static type checking), support and catch errors earlier
- Maintain the flexibility of duck typing
- Leverage type checking for classes you are unable to modify.
If you want to learn more about Protocols and type hinting in Python, check out the official Python documentation on the typing module, or explore advanced static type checking tools like mypy.
Happy coding, and may your ducks always quack with type safety!
You can find more of my content, including my newsletter here
The above is the detailed content of Duck Typing Meets Type Hints: Using Protocols in Python. For more information, please follow other related articles on the PHP Chinese website!

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.