Skip to content

Commit 22c738a

Browse files
xiangyan99kashifkhankristapratico
authored
Improve typing (Azure#28216)
* Impove typing * updates * update * updates * updates * updates * update * update * Update sdk/search/azure-search-documents/azure/search/documents/_utils.py Co-authored-by: Kashif Khan <[email protected]> * update * updates * Update sdk/search/azure-search-documents/azure/search/documents/aio/_search_indexing_buffered_sender_async.py Co-authored-by: Krista Pratico <[email protected]> * Updates * update * remove _flatten_args * add _flatten_args back * update * update Co-authored-by: Kashif Khan <[email protected]> Co-authored-by: Krista Pratico <[email protected]>
1 parent a17fed2 commit 22c738a

29 files changed

+872
-1012
lines changed

sdk/search/azure-search-documents/azure/search/documents/_headers_mixin.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,15 @@
44
# license information.
55
# --------------------------------------------------------------------------
66

7-
from typing import TYPE_CHECKING
7+
from typing import Optional, Dict, Any
88

9-
if TYPE_CHECKING:
10-
from typing import Optional
119

12-
13-
class HeadersMixin(object):
10+
class HeadersMixin:
1411
@property
15-
def _headers(self):
16-
# type() -> dict
12+
def _headers(self) -> Dict[str, Any]:
1713
return {"api-key": self._credential.key, "Accept": self._ODATA_ACCEPT}
1814

19-
def _merge_client_headers(self, headers):
20-
# type(Optional[dict]) -> dict
15+
def _merge_client_headers(self, headers: Optional[Dict[str, Any]]) -> Dict[str, Any]:
2116
if self._aad:
2217
return headers
2318
headers = headers or {}

sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,18 @@
33
# Licensed under the MIT License. See License.txt in the project root for
44
# license information.
55
# --------------------------------------------------------------------------
6-
from typing import TYPE_CHECKING
6+
from typing import Union, List, Dict, Any
77
from threading import Lock
88

99
from ._generated.models import IndexAction
1010

11-
if TYPE_CHECKING:
12-
# pylint:disable=unused-import,ungrouped-imports
13-
from typing import List
1411

15-
16-
def _flatten_args(args):
17-
# type (Union[List[dict], List[List[dict]]]) -> List[dict]
12+
def _flatten_args(args: Union[List[Dict], List[List[Dict]]]) -> List[Dict]:
1813
if len(args) == 1 and isinstance(args[0], (list, tuple)):
1914
return args[0]
2015
return args
2116

22-
23-
class IndexDocumentsBatch(object):
17+
class IndexDocumentsBatch:
2418
"""Represent a batch of update operations for documents in an Azure
2519
Search index.
2620
@@ -29,17 +23,14 @@ class IndexDocumentsBatch(object):
2923
3024
"""
3125

32-
def __init__(self):
33-
# type: () -> None
34-
self._actions = [] # type: List[IndexAction]
26+
def __init__(self) -> None:
27+
self._actions: List[IndexAction] = []
3528
self._lock = Lock()
3629

37-
def __repr__(self):
38-
# type: () -> str
30+
def __repr__(self) -> str:
3931
return "<IndexDocumentsBatch [{} actions]>".format(len(self.actions))[:1024]
4032

41-
def add_upload_actions(self, *documents):
42-
# type (Union[List[dict], List[List[dict]]]) -> List[IndexAction]
33+
def add_upload_actions(self, *documents: Union[List[Dict], List[List[Dict]]]) -> List[IndexAction]:
4334
"""Add documents to upload to the Azure search index.
4435
4536
An upload action is similar to an "upsert" where the document will be
@@ -48,16 +39,16 @@ def add_upload_actions(self, *documents):
4839
4940
:param documents: Documents to upload to an Azure search index. May be
5041
a single list of documents, or documents as individual parameters.
51-
:type documents: dict or list[dict]
42+
:type documents: Dict or List[Dict]
5243
:return: the added actions
5344
:rtype: List[IndexAction]
5445
"""
5546
return self._extend_batch(_flatten_args(documents), "upload")
5647

5748
def add_delete_actions(
58-
self, *documents, **kwargs
59-
): # pylint: disable=unused-argument
60-
# type (Union[List[dict], List[List[dict]]]) -> List[IndexAction]
49+
self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any
50+
) -> List[IndexAction]:
51+
# pylint: disable=unused-argument
6152
"""Add documents to delete to the Azure search index.
6253
6354
Delete removes the specified document from the index. Any field you
@@ -71,16 +62,16 @@ def add_delete_actions(
7162
7263
:param documents: Documents to delete from an Azure search index. May be
7364
a single list of documents, or documents as individual parameters.
74-
:type documents: dict or list[dict]
65+
:type documents: Dict or List[Dict]
7566
:return: the added actions
7667
:rtype: List[IndexAction]
7768
"""
7869
return self._extend_batch(_flatten_args(documents), "delete")
7970

8071
def add_merge_actions(
81-
self, *documents, **kwargs
82-
): # pylint: disable=unused-argument
83-
# type (Union[List[dict], List[List[dict]]]) -> List[IndexAction]
72+
self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any
73+
) -> List[IndexAction]:
74+
# pylint: disable=unused-argument
8475
"""Add documents to merge in to existing documents in the Azure search
8576
index.
8677
@@ -91,16 +82,16 @@ def add_merge_actions(
9182
9283
:param documents: Documents to merge into an Azure search index. May be
9384
a single list of documents, or documents as individual parameters.
94-
:type documents: dict or list[dict]
85+
:type documents: Dict or List[Dict]
9586
:return: the added actions
9687
:rtype: List[IndexAction]
9788
"""
9889
return self._extend_batch(_flatten_args(documents), "merge")
9990

10091
def add_merge_or_upload_actions(
101-
self, *documents, **kwargs
102-
): # pylint: disable=unused-argument
103-
# type (Union[List[dict], List[List[dict]]]) -> List[IndexAction]
92+
self, *documents: Union[List[Dict], List[List[Dict]]], **kwargs: Any
93+
) -> List[IndexAction]:
94+
# pylint: disable=unused-argument
10495
"""Add documents to merge in to existing documents in the Azure search
10596
index, or upload if they do not yet exist.
10697
@@ -111,23 +102,21 @@ def add_merge_or_upload_actions(
111102
:param documents: Documents to merge or upload into an Azure search
112103
index. May be a single list of documents, or documents as individual
113104
parameters.
114-
:type documents: dict or list[dict]
105+
:type documents: Dict or List[Dict]
115106
:return: the added actions
116107
:rtype: List[IndexAction]
117108
"""
118109
return self._extend_batch(_flatten_args(documents), "mergeOrUpload")
119110

120111
@property
121-
def actions(self):
122-
# type: () -> List[IndexAction]
112+
def actions(self) -> List[IndexAction]:
123113
"""The list of currently index actions to index.
124114
125115
:rtype: List[IndexAction]
126116
"""
127117
return list(self._actions)
128118

129-
def dequeue_actions(self, **kwargs): # pylint: disable=unused-argument
130-
# type: () -> List[IndexAction]
119+
def dequeue_actions(self, **kwargs: Any) -> List[IndexAction]: # pylint: disable=unused-argument
131120
"""Get the list of currently configured index actions and clear it.
132121
133122
:rtype: List[IndexAction]
@@ -137,8 +126,10 @@ def dequeue_actions(self, **kwargs): # pylint: disable=unused-argument
137126
self._actions = []
138127
return result
139128

140-
def enqueue_actions(self, new_actions, **kwargs): # pylint: disable=unused-argument
141-
# type: (Union[IndexAction, List[IndexAction]]) -> None
129+
def enqueue_actions(
130+
self, new_actions: Union[IndexAction, List[IndexAction]], **kwargs: Any
131+
) -> None:
132+
# pylint: disable=unused-argument
142133
"""Enqueue a list of index actions to index."""
143134
if isinstance(new_actions, IndexAction):
144135
with self._lock:
@@ -147,8 +138,7 @@ def enqueue_actions(self, new_actions, **kwargs): # pylint: disable=unused-argu
147138
with self._lock:
148139
self._actions.extend(new_actions)
149140

150-
def _extend_batch(self, documents, action_type):
151-
# type: (List[dict], str) -> List[IndexAction]
141+
def _extend_batch(self, documents: List[Dict], action_type: str) -> List[IndexAction]:
152142
new_actions = [
153143
IndexAction(additional_properties=document, action_type=action_type)
154144
for document in documents

sdk/search/azure-search-documents/azure/search/documents/_paging.py

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,15 @@
33
# Licensed under the MIT License. See License.txt in the project root for
44
# license information.
55
# --------------------------------------------------------------------------
6-
from typing import TYPE_CHECKING
6+
from typing import List, Optional, Dict
77

88
import base64
99
import itertools
1010
import json
1111

1212
from azure.core.paging import ItemPaged, PageIterator, ReturnType
1313
from ._generated.models import SearchRequest
14-
15-
if TYPE_CHECKING:
16-
# pylint:disable=unused-import,ungrouped-imports
17-
from typing import Any, Union
18-
from ..documents.models import AnswerResult
14+
from ..documents.models import AnswerResult
1915

2016

2117
def convert_search_result(result):
@@ -45,12 +41,11 @@ def unpack_continuation_token(token):
4541

4642

4743
class SearchItemPaged(ItemPaged[ReturnType]):
48-
def __init__(self, *args, **kwargs):
44+
def __init__(self, *args, **kwargs) -> None:
4945
super(SearchItemPaged, self).__init__(*args, **kwargs)
5046
self._first_page_iterator_instance = None
5147

52-
def __next__(self):
53-
# type: () -> ReturnType
48+
def __next__(self) -> ReturnType:
5449
if self._page_iterator is None:
5550
first_iterator = self._first_iterator_instance()
5651
self._page_iterator = itertools.chain.from_iterable(first_iterator)
@@ -61,29 +56,25 @@ def _first_iterator_instance(self):
6156
self._first_page_iterator_instance = self.by_page()
6257
return self._first_page_iterator_instance
6358

64-
def get_facets(self):
65-
# type: () -> Union[dict, None]
59+
def get_facets(self) -> Optional[Dict]:
6660
"""Return any facet results if faceting was requested."""
6761
return self._first_iterator_instance().get_facets()
6862

69-
def get_coverage(self):
70-
# type: () -> float
63+
def get_coverage(self) -> float:
7164
"""Return the coverage percentage, if `minimum_coverage` was
7265
specificied for the query.
7366
7467
"""
7568
return self._first_iterator_instance().get_coverage()
7669

77-
def get_count(self):
78-
# type: () -> float
70+
def get_count(self) -> int:
7971
"""Return the count of results if `include_total_count` was
8072
set for the query.
8173
8274
"""
8375
return self._first_iterator_instance().get_count()
8476

85-
def get_answers(self):
86-
# type: () -> Union[list[AnswerResult], None]
77+
def get_answers(self) -> Optional[List[AnswerResult]]:
8778
"""Return answers."""
8879
return self._first_iterator_instance().get_answers()
8980

@@ -104,7 +95,7 @@ def wrapper(self, *args, **kw):
10495

10596

10697
class SearchPageIterator(PageIterator):
107-
def __init__(self, client, initial_query, kwargs, continuation_token=None):
98+
def __init__(self, client, initial_query, kwargs, continuation_token=None) -> None:
10899
super(SearchPageIterator, self).__init__(
109100
get_next=self._get_next_cb,
110101
extract_data=self._extract_data_cb,
@@ -128,7 +119,7 @@ def _get_next_cb(self, continuation_token):
128119
search_request=next_page_request, **self._kwargs
129120
)
130121

131-
def _extract_data_cb(self, response): # pylint:disable=no-self-use
122+
def _extract_data_cb(self, response):
132123
continuation_token = pack_continuation_token(
133124
response, api_version=self._api_version
134125
)

sdk/search/azure-search-documents/azure/search/documents/_queries.py

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,25 @@
33
# Licensed under the MIT License. See License.txt in the project root for
44
# license information.
55
# --------------------------------------------------------------------------
6-
from typing import TYPE_CHECKING
7-
6+
from typing import Type, Union
87
from ._generated.models import AutocompleteRequest, SearchRequest, SuggestRequest
98

10-
if TYPE_CHECKING:
11-
# pylint:disable=unused-import
12-
from typing import Any, List, Type, Union
13-
149

15-
class _QueryBase(object):
10+
class _QueryBase:
1611

17-
_request_type = (
12+
_request_type: Union[Type[AutocompleteRequest], Type[SearchRequest], Type[SuggestRequest]] = (
1813
None
19-
) # type: Union[Type[AutocompleteRequest], Type[SearchRequest], Type[SuggestRequest]]
14+
)
2015

21-
def __init__(self, **kwargs):
22-
# type: (**Any) -> None
16+
def __init__(self, **kwargs) -> None:
2317
self._request = self._request_type(**kwargs) # pylint:disable=not-callable
2418

25-
def __repr__(self):
26-
# type: () -> str
19+
def __repr__(self) -> str:
2720
return "<{} [{}]>".format(self.__class__.__name__, self._request.search_text)[
2821
:1024
2922
]
3023

31-
def filter(self, expression):
32-
# type: (str) -> None
24+
def filter(self, expression: str) -> None:
3325
"""Add a `filter` expression for the search results.
3426
3527
:param expression: An ODate expression of for the query filter.
@@ -58,25 +50,23 @@ class SearchQuery(_QueryBase):
5850

5951
__doc__ = SearchRequest.__doc__
6052

61-
def order_by(self, *fields):
62-
# type: (*str) -> None
53+
def order_by(self, *fields: str) -> None:
6354
"""Update the `orderby` property for the search results.
6455
65-
:param fields: An list of fields for the query result to be ordered by.
66-
:type expression: str
56+
:param fields: A list of fields for the query result to be ordered by.
57+
:type fields: str
6758
:raises: ValueError
6859
"""
6960
if not fields:
7061
raise ValueError("At least one field must be provided")
7162

7263
self._request.order_by = ",".join(fields)
7364

74-
def select(self, *fields):
75-
# type: (*str) -> None
65+
def select(self, *fields: str) -> None:
7666
"""Update the `select` property for the search results.
7767
78-
:param fields: An list of fields for the query result to return.
79-
:type expression: str
68+
:param fields: A list of fields for the query result to return.
69+
:type fields: str
8070
:raises: ValueError
8171
"""
8272
if not fields:
@@ -97,12 +87,11 @@ class SuggestQuery(_QueryBase):
9787

9888
__doc__ = SuggestRequest.__doc__
9989

100-
def select(self, *fields):
101-
# type: (*str) -> None
90+
def select(self, *fields: str) -> None:
10291
"""Update the `select` property for the search results.
10392
104-
:param fields: An list of fields for the query result to return.
105-
:type expression: str
93+
:param fields: A list of fields for the query result to return.
94+
:type fields: str
10695
:raises: ValueError
10796
"""
10897
if not fields:

0 commit comments

Comments
 (0)