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. Practical Decorators in Python Libraries
  • 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

On this page

  • Practical Decorators in Python Libraries
    • 1. FastAPI Decorators
      • Basic Usage and Explanation
    • 2. Numba Decorators
      • Basic Usage and Limitations
    • 3. Pytest Decorators
      • Basic Usage
    • Conclusion

Practical Decorators in Python Libraries

Course
Advanced Python
Explore practical usage of decorators in popular Python libraries including FastAPI, Numba, and Pytest. Learn how to leverage these powerful tools in your Python projects.
Author

Remi Genet

Published

2024-10-21

Practical Decorators in Python Libraries

This course builds upon your understanding of basic decorators and explores their practical usage in popular Python libraries. We’ll focus on FastAPI, Numba, and Pytest, explaining how to use their decorators effectively in your projects.

1. FastAPI Decorators

FastAPI is a modern, fast web framework for building APIs with Python. It makes extensive use of decorators for routing, request handling, and more.

Basic Usage and Explanation

In this expanded FastAPI example:

  1. @app.get("/") defines a route for GET requests to the root URL. It returns a simple JSON response.

  2. @app.get("/items/{item_id}") sets up a route with a path parameter item_id. The Path function is used to add validation and metadata to the path parameter. The Query function is used to define an optional query parameter q.

  3. @app.post("/items/") defines a route for POST requests to create new items. It uses a Pydantic model Item for request body validation.

FastAPI’s decorators handle several tasks automatically: - Route registration - Request parsing and validation - Dependency injection - Response serialization - Automatic API documentation generation

These decorators allow you to focus on your business logic while FastAPI handles the complexities of building a robust API.

2. Numba Decorators

Numba is a Just-In-Time (JIT) compiler for Python that can significantly speed up numerical Python code by compiling it to native machine instructions.

Basic Usage and Limitations

The @jit(nopython=True) decorator tells Numba to compile the function to machine code without using the Python interpreter. This can lead to significant performance improvements, especially for numerical computations.

Important notes about Numba: - Numba compiles Python functions to optimized machine code at runtime. - It works best with numerical algorithms and NumPy arrays. - The nopython=True mode provides the best performance but has limitations on the Python features it supports. - Numba doesn’t support all Python types or features. It works best with simple numeric types, NumPy arrays, and a subset of Python and NumPy functions. - External libraries (except for NumPy and a few others) are generally not supported in Numba-compiled functions.

3. Pytest Decorators

Pytest is a powerful testing framework for Python that uses decorators to enhance and customize test behavior.

Basic Usage

In this Pytest example:

  1. @pytest.fixture defines a fixture named example_fixture. Fixtures in Pytest are used to provide data or objects to tests.

  2. @pytest.mark.parametrize allows you to run the same test function multiple times with different inputs. It’s great for testing multiple scenarios without duplicating code.

  3. @pytest.mark.slow is a custom marker. You can use markers to categorize tests and selectively run them.

Pytest’s decorators allow you to: - Define and manage test fixtures - Parameterize tests for multiple inputs - Mark tests for organization and selective execution - Modify test behavior or skip tests based on conditions

These decorators make it easier to write comprehensive, maintainable test suites.

Conclusion

Decorators in libraries like FastAPI, Numba, and Pytest showcase the power and flexibility of Python’s decorator system. They allow these libraries to provide clean, intuitive APIs that enhance productivity:

  • FastAPI’s decorators simplify the process of building robust, well-documented APIs.
  • Numba’s JIT decorator can dramatically speed up numerical computations, though with some limitations on supported Python features.
  • Pytest’s decorators make it easier to write, organize, and customize tests.

By understanding and leveraging these library-specific decorators, you can write more efficient, maintainable, and expressive Python code. Remember to consult each library’s documentation for the most up-to-date and detailed information on their decorator usage and capabilities.

Back to top
Built-in Decorators and Standard Library Decorators in Python
TP: Monte Carlo Option Pricing with Decorators

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