elastic / elasticsearch-dsl-py

High level Python client for Elasticsearch
http://elasticsearch-dsl.readthedocs.org
Apache License 2.0
3.84k stars 802 forks source link

type hints for document, search_base and utils classes #1851

Closed miguelgrinberg closed 5 months ago

miguelgrinberg commented 5 months ago

This is another somewhat large PR that tackles the difficult area of typing search results. I started adding types to document_base.py and {_async|_sync}/document.py, plus any other related files that were necessary, which are many.

I set out to support fully typed results when you are searching using a document class. Here is an example from the vectors.py example, where the search automagically returns WorkplaceDoc instances as search results, just because the search object was created by calling WorkplaceDoc.search():

Screenshot 2024-06-27 at 4 33 08 PM

This is implemented using generics. The search class is now represented as Search[DocumentClass], where results are returned as instances of DocumentClass. If using Search alone, the default Hit object is used for typing, matching the runtime behavior.

Adding this required plumbing the generic type through a large part of the library. I also made some other changes along the way, to help me reach the goal of fully typing the document source files: