Programmation Orientée Objet en Python
  • Back to Main Website
  • Home
  • Introduction: Histoire et Concepts
    • Introduction: Histoire et Concepts
    • Histoire de la programmation
    • Première Structuration des données
    • Naissance de la POO
    • Python: tout n’est qu’objet
    • Python : Simplicité des objets et performance sous-jacente
    • Classes en Python : Concepts fondamentaux

    • Travaux Pratiques
    • Construire sa propre Liste
    • Construire son propre DataFrame
  • Encapsulation, Héritage, Composition et Dunder
    • Encapsulation, Heritage, Composition et Dunder
    • Encapsulation en Python
    • Héritage en Python : Concept et intérêt
    • Héritage vs Composition
    • Méthodes Dunder en Python
    • Python call Method: A Fun Exploration

    • Travaux Pratiques
    • TP: Heritage avec le pricing d’option
    • TP : Ajouter des méthodes dunder à DataFrameSimple
    • TP : Étendre la classe Liste avec des méthodes dunder
    • TP: Dunder Method with Tensor for Automatic Differentiation
  • Polymorphisme et Surcharge
    • Polymorphisme et Surcharge
    • Polymorphism in Object-Oriented Programming
    • Polymorphism in Python: Function Overloading and Type Checking
    • Class Creation: Standard vs type()
    • Type Hinting, Typing Module, and Linters in Python
    • Abstract Classes
    • Protocol Classes

    • Travaux Pratiques
    • TP
  • Decorators
    • Design Patterns
    • The decorator pattern
    • Decorator Practically
    • Built-in Decorators and Standard Library Decorators in Python
    • Practical Decorators in Python Libraries

    • Travaux Pratiques
    • TP: Monte Carlo Option Pricing with Decorators
    • TP: Optimizing Heston Model Monte Carlo Simulation
  • Project Management and Packaging
    • Project and Package
    • Organizing Python Projects
    • Understanding imports
    • Python Package Management and Virtual Environments
    • Unit Testing in Python

    • Travaux Pratiques
    • TP: Creating a Linear Regression Package
  • Design Patterns
    • OOP Design Patterns
    • Python-Specific Design Patterns
    • Creation Design Patterns
    • Structural Design Patterns
    • Behavioral Design Pattern

    • Travaux Pratiques
    • TP
  • Sujets de Projets possibles
    • Projets
    • Projets POO - 2024-2025
  • Code source
  1. Protocol Classes
  • Polymorphisme et Surcharge
  • Polymorphism in Object-Oriented Programming
  • Polymorphism in Python: Function Overloading and Type Checking
  • Class Creation: Standard vs type()
  • Type Hinting, Typing Module, and Linters in Python
  • Abstract Classes
  • Protocol Classes
  • Travaux Pratiques
    • TP

On this page

  • Protocol Classes in Python
    • Introduction to Protocols
    • Key Concepts
    • Basic Usage of Protocols
    • Advantages of Protocols
    • More Complex Example
    • Runtime Checkable Protocols
    • Conclusion

Protocol Classes

Cours
Fondamentaux
Learn about Protocol classes in Python, how to define and use them, and the advantages of using Protocols for defining interfaces and structural subtyping.
Author

Remi Genet

Published

2024-10-21

Protocol Classes in Python


Introduction to Protocols

Protocols, introduced in Python 3.8, provide a way to define structural subtyping (often called “duck typing”). They allow you to define interfaces in a more flexible and Pythonic way compared to abstract base classes.

Key Concepts

  1. Structural Subtyping: An object is considered a subtype if it has the required methods and attributes, regardless of inheritance.
  2. No Runtime Enforcement: Protocols are primarily used for static type checking and don’t enforce method implementation at runtime.
  3. Flexibility: Classes don’t need to explicitly inherit from a Protocol to be considered compatible.

Basic Usage of Protocols

To use Protocols, you need to import from the typing module:

In this example: - Drawable is a Protocol that defines an interface with a draw method. - Circle is compatible with Drawable because it has a draw method, even though it doesn’t explicitly inherit from Drawable.

Advantages of Protocols

  1. Flexibility: You can define interfaces for existing classes without modifying them.
  2. Duck Typing: Aligns well with Python’s “duck typing” philosophy.
  3. Static Type Checking: Provides benefits of static typing without runtime overhead.
  4. Backwards Compatibility: Can be used with existing codebases without modification.

More Complex Example

Let’s look at a more comprehensive example using Protocols:

In this example: - We define multiple Protocols: Sized, Appendable, and StringContainer. - StringContainer combines multiple Protocols. - MyList is compatible with StringContainer because it implements all required methods. - process_data can work with any object that satisfies the StringContainer Protocol.

Runtime Checkable Protocols

While Protocols are primarily for static type checking, you can make them runtime-checkable:

The @runtime_checkable decorator allows isinstance() checks, but be cautious as it only checks for the existence of the methods, not their signatures.

Conclusion

Protocols in Python provide a flexible and powerful way to define interfaces. They offer the benefits of static typing and interface definition while maintaining Python’s dynamic and duck-typed nature. Protocols are especially useful in large codebases, for defining clear contracts between different parts of a system, and for working with existing code that can’t be modified to inherit from specific base classes.

Back to top
Abstract Classes
TP

Programmation Orienté Object en Python, Rémi Genet.
Licence
Code source disponible sur Github

 

Site construit avec et Quarto
Inspiration pour la mise en forme du site ici
Code source disponible sur GitHub