Skip to content

Commit 5aecb16

Browse files
authored
Remove the simplest .pyi stubs
1 parent 2ee9850 commit 5aecb16

File tree

14 files changed

+112
-319
lines changed

14 files changed

+112
-319
lines changed

elasticsearch/_async/compat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from asyncio import get_running_loop
2929
except ImportError:
3030

31-
def get_running_loop():
31+
def get_running_loop() -> asyncio.AbstractEventLoop:
3232
loop = asyncio.get_event_loop()
3333
if not loop.is_running():
3434
raise RuntimeError("no running event loop")

elasticsearch/_async/compat.pyi

Lines changed: 0 additions & 20 deletions
This file was deleted.

elasticsearch/client/utils.py

Lines changed: 57 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,33 @@
2020
import weakref
2121
from datetime import date, datetime
2222
from functools import wraps
23+
from typing import (
24+
TYPE_CHECKING,
25+
Any,
26+
Callable,
27+
Collection,
28+
Dict,
29+
List,
30+
Optional,
31+
Tuple,
32+
TypeVar,
33+
Union,
34+
)
2335

2436
from ..compat import quote, string_types, to_bytes, to_str, unquote, urlparse
37+
from ..serializer import Serializer
38+
from ..transport import Transport
39+
40+
if TYPE_CHECKING:
41+
from ..client import Elasticsearch
2542

2643
# parts of URL to be omitted
27-
SKIP_IN_PATH = (None, "", b"", [], ())
44+
SKIP_IN_PATH: Collection[Any] = (None, "", b"", [], ())
2845

2946

30-
def _normalize_hosts(hosts):
47+
def _normalize_hosts(
48+
hosts: Optional[Union[str, Collection[Union[str, Dict[str, Any]]]]]
49+
) -> List[Dict[str, Any]]:
3150
"""
3251
Helper function to transform hosts argument to
3352
:class:`~elasticsearch.Elasticsearch` to a list of dicts.
@@ -40,15 +59,15 @@ def _normalize_hosts(hosts):
4059
if isinstance(hosts, string_types):
4160
hosts = [hosts]
4261

43-
out = []
62+
out: List[Dict[str, Any]] = []
4463
# normalize hosts to dicts
4564
for host in hosts:
4665
if isinstance(host, string_types):
4766
if "://" not in host:
4867
host = f"//{host}"
4968

5069
parsed_url = urlparse(host)
51-
h = {"host": parsed_url.hostname}
70+
h: Dict[str, Any] = {"host": parsed_url.hostname}
5271

5372
if parsed_url.port:
5473
h["port"] = parsed_url.port
@@ -59,20 +78,20 @@ def _normalize_hosts(hosts):
5978

6079
if parsed_url.username or parsed_url.password:
6180
h["http_auth"] = "{}:{}".format(
62-
unquote(parsed_url.username),
63-
unquote(parsed_url.password),
81+
unquote(parsed_url.username or ""),
82+
unquote(parsed_url.password or ""),
6483
)
6584

6685
if parsed_url.path and parsed_url.path != "/":
6786
h["url_prefix"] = parsed_url.path
6887

6988
out.append(h)
7089
else:
71-
out.append(host)
90+
out.append(host) # type: ignore
7291
return out
7392

7493

75-
def _escape(value):
94+
def _escape(value: Any) -> Union[str, bytes]:
7695
"""
7796
Escape a single value of a URL string or a query parameter. If it is a list
7897
or tuple, turn it into a comma-separated string first.
@@ -96,11 +115,11 @@ def _escape(value):
96115

97116
# encode strings to utf-8
98117
if not isinstance(value, str):
99-
value = str(value)
118+
return str(value).encode("utf-8")
100119
return value.encode("utf-8")
101120

102121

103-
def _make_path(*parts):
122+
def _make_path(*parts: Any) -> str:
104123
"""
105124
Create a URL string from parts, omit all `None` values and empty strings.
106125
Convert lists and tuples to comma separated values.
@@ -115,18 +134,27 @@ def _make_path(*parts):
115134

116135

117136
# parameters that apply to all methods
118-
GLOBAL_PARAMS = ("pretty", "human", "error_trace", "format", "filter_path")
119-
120-
121-
def query_params(*es_query_params):
137+
GLOBAL_PARAMS: Tuple[str, ...] = (
138+
"pretty",
139+
"human",
140+
"error_trace",
141+
"format",
142+
"filter_path",
143+
)
144+
T = TypeVar("T")
145+
146+
147+
def query_params(
148+
*es_query_params: str,
149+
) -> Callable[[Callable[..., T]], Callable[..., T]]:
122150
"""
123151
Decorator that pops all accepted parameters from method's kwargs and puts
124152
them in the params argument.
125153
"""
126154

127-
def _wrapper(func):
155+
def _wrapper(func: Any) -> Any:
128156
@wraps(func)
129-
def _wrapped(*args, **kwargs):
157+
def _wrapped(*args: Any, **kwargs: Any) -> Any:
130158
params = (kwargs.pop("params", None) or {}).copy()
131159
headers = {
132160
k.lower(): v
@@ -165,7 +193,9 @@ def _wrapped(*args, **kwargs):
165193
return _wrapper
166194

167195

168-
def _bulk_body(serializer, body):
196+
def _bulk_body(
197+
serializer: Serializer, body: Union[str, bytes, Collection[Any]]
198+
) -> Union[str, bytes]:
169199
# if not passed in a string, serialize items and join by newline
170200
if not isinstance(body, string_types):
171201
body = "\n".join(map(serializer.dumps, body))
@@ -174,13 +204,15 @@ def _bulk_body(serializer, body):
174204
if isinstance(body, bytes):
175205
if not body.endswith(b"\n"):
176206
body += b"\n"
177-
elif isinstance(body, string_types) and not body.endswith("\n"):
207+
elif isinstance(body, str) and not body.endswith("\n"):
178208
body += "\n"
179209

180210
return body
181211

182212

183-
def _base64_auth_header(auth_value):
213+
def _base64_auth_header(
214+
auth_value: Union[List[str], Tuple[str, ...], str, bytes]
215+
) -> str:
184216
"""Takes either a 2-tuple or a base64-encoded string
185217
and returns a base64-encoded string to be used
186218
as an HTTP authorization header.
@@ -191,17 +223,19 @@ def _base64_auth_header(auth_value):
191223

192224

193225
class NamespacedClient:
194-
def __init__(self, client):
226+
client: "Elasticsearch"
227+
228+
def __init__(self, client: "Elasticsearch") -> None:
195229
self.client = client
196230

197231
@property
198-
def transport(self):
232+
def transport(self) -> Transport:
199233
return self.client.transport
200234

201235

202236
class AddonClient(NamespacedClient):
203237
@classmethod
204-
def infect_client(cls, client):
238+
def infect_client(cls, client: "Elasticsearch") -> "Elasticsearch":
205239
addon = cls(weakref.proxy(client))
206-
setattr(client, cls.namespace, addon)
240+
setattr(client, cls.namespace, addon) # type: ignore
207241
return client

elasticsearch/client/utils.pyi

Lines changed: 0 additions & 56 deletions
This file was deleted.

elasticsearch/compat.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,19 @@
1616
# under the License.
1717

1818
from queue import Queue
19+
from typing import Tuple, Type, Union
1920
from urllib.parse import quote, quote_plus, unquote, urlencode, urlparse
2021

21-
string_types = str, bytes
22+
string_types: Tuple[Type[str], Type[bytes]] = (str, bytes)
2223

2324

24-
def to_str(x, encoding="ascii"):
25+
def to_str(x: Union[str, bytes], encoding: str = "ascii") -> str:
2526
if not isinstance(x, str):
2627
return x.decode(encoding)
2728
return x
2829

2930

30-
def to_bytes(x, encoding="ascii"):
31+
def to_bytes(x: Union[str, bytes], encoding: str = "ascii") -> bytes:
3132
if not isinstance(x, bytes):
3233
return x.encode(encoding)
3334
return x
@@ -39,7 +40,7 @@ def to_bytes(x, encoding="ascii"):
3940
from collections import Mapping
4041

4142

42-
reraise_exceptions = (RecursionError,)
43+
reraise_exceptions: Tuple[Type[Exception], ...] = (RecursionError,)
4344

4445
try:
4546
import asyncio

elasticsearch/compat.pyi

Lines changed: 0 additions & 31 deletions
This file was deleted.

0 commit comments

Comments
 (0)