-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
_self_injecting.py
211 lines (171 loc) · 7.14 KB
/
_self_injecting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2020-2022, Faster Speeding
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
__all__: list[str] = ["AsyncSelfInjecting", "SelfInjecting"]
import typing
from collections import abc as collections
from . import abc as alluka
_CallbackSigT = typing.TypeVar("_CallbackSigT", bound=alluka.CallbackSig[typing.Any])
_SyncCallbackT = typing.TypeVar("_SyncCallbackT", bound=collections.Callable[..., typing.Any])
_T = typing.TypeVar("_T")
_CoroT = collections.Coroutine[typing.Any, typing.Any, _T]
class AsyncSelfInjecting(alluka.AsyncSelfInjecting[_CallbackSigT]):
"""Class used to link a sync function to a client to make it self-injecting.
Examples
--------
```py
async def callback(database: Database = alluka.inject(type=Database)) -> None:
await database.do_something()
...
client = alluka.Client()
injecting_callback = alluka.AsyncSelfInjecting(callback, client)
await injecting_callback()
```
Alternatively [alluka.abc.Client.as_async_self_injecting][] may be used:
```py
client = alluka.Client()
@client.as_async_self_injecting
async def callback(database: Database = alluka.inject(type=Database)) -> None:
...
```
"""
__slots__ = ("_callback", "_client", "_get_client")
def __init__(
self, client: typing.Union[alluka.Client, collections.Callable[[], alluka.Client]], callback: _CallbackSigT, /
) -> None:
"""Initialise a self injecting callback.
Parameters
----------
client
Either the injection client instance to use to resolve dependencies
or a callback used to get the client instance.
callback : alluka.abc.CallbackSig
The callback to make self-injecting.
This may be sync or async.
Raises
------
ValueError
If `callback` has any injected arguments which can only be passed
positionally.
"""
self._callback = callback
if isinstance(client, alluka.Client):
self._client: typing.Optional[alluka.Client] = client
self._get_client: typing.Optional[collections.Callable[[], alluka.Client]] = None
else:
self._client = None
self._get_client = client
@typing.overload
async def __call__(
self: AsyncSelfInjecting[collections.Callable[..., _CoroT[_T]]], *args: typing.Any, **kwargs: typing.Any
) -> _T:
...
@typing.overload
async def __call__(
self: AsyncSelfInjecting[collections.Callable[..., _T]], *args: typing.Any, **kwargs: typing.Any
) -> _T:
...
async def __call__(
self: typing.Union[
AsyncSelfInjecting[collections.Callable[..., _T]], AsyncSelfInjecting[collections.Callable[..., _CoroT[_T]]]
],
*args: typing.Any,
**kwargs: typing.Any,
) -> _T:
# <<inherited docstring from alluka.abc.AsyncSelfInjecting>>.
client = self._client
if not client:
assert self._get_client
client = self._get_client()
return await client.call_with_async_di(self._callback, *args, **kwargs)
@property
def callback(self) -> _CallbackSigT:
# <<inherited docstring from alluka.abc.AsyncSelfInjecting>>.
return self._callback
class SelfInjecting(alluka.SelfInjecting[_SyncCallbackT]):
"""Class used to link a sync function to a client to make it self-injecting.
!!! note
This executes the callback synchronously and therefore will error if
any of the callback's dependencies are async.
Examples
--------
```py
async def callback(database: Database = alluka.inject(type=Database)) -> None:
await database.do_something()
...
client = alluka.Client()
injecting_callback = alluka.SelfInjecting(callback, client)
await injecting_callback()
```
Alternatively [alluka.abc.Client.as_self_injecting][] may be used:
```py
client = alluka.Client()
@client.as_self_injecting
async def callback(database: Database = alluka.inject(type=Database)) -> None:
...
```
"""
__slots__ = ("_callback", "_client", "_get_client")
def __init__(
self, client: typing.Union[alluka.Client, collections.Callable[[], alluka.Client]], callback: _SyncCallbackT, /
) -> None:
"""Initialise a sync self injecting callback.
Parameters
----------
client
Either the injection client instance to use to resolve dependencies
or a callback used to get the client instance.
callback : collections.abc.Callable
The callback to make self-injecting.
Raises
------
ValueError
If `callback` has any injected arguments which can only be passed
positionally.
"""
self._callback = callback
if isinstance(client, alluka.Client):
self._client: typing.Optional[alluka.Client] = client
self._get_client: typing.Optional[collections.Callable[[], alluka.Client]] = None
else:
self._client = None
self._get_client = client
def __call__(self: SelfInjecting[collections.Callable[..., _T]], *args: typing.Any, **kwargs: typing.Any) -> _T:
# <<inherited docstring from alluka.abc.SelfInjecting>>.
client = self._client
if not client:
assert self._get_client
client = self._get_client()
return client.call_with_di(self._callback, *args, **kwargs)
@property
def callback(self) -> _SyncCallbackT:
# <<inherited docstring from alluka.abc.SelfInjecting>>.
return self._callback