MCPcopy Index your code
hub / github.com/dry-python/returns / ask

Method ask

returns/context/requires_context.py:234–313  ·  view source on GitHub ↗

Get current context to use the dependencies. It is a common scenario when you need to use the environment. For example, you want to do some context-related computation, but you don't have the context instance at your disposal. That's where ``.ask()`` becomes

(cls)

Source from the content-addressed store, hash-verified

232
233 @classmethod
234 def ask(cls) -> RequiresContext[_EnvType_contra, _EnvType_contra]:
235 """
236 Get current context to use the dependencies.
237
238 It is a common scenario when you need to use the environment.
239 For example, you want to do some context-related computation,
240 but you don't have the context instance at your disposal.
241 That's where ``.ask()`` becomes useful!
242
243 .. code:: python
244
245 >>> from typing_extensions import TypedDict
246 >>> class Deps(TypedDict):
247 ... message: str
248
249 >>> def first(lg: bool) -> RequiresContext[int, Deps]:
250 ... # `deps` has `Deps` type here:
251 ... return RequiresContext(
252 ... lambda deps: deps['message'] if lg else 'error',
253 ... )
254
255 >>> def second(text: str) -> RequiresContext[int, Deps]:
256 ... return first(len(text) > 3)
257
258 >>> assert second('abc')({'message': 'ok'}) == 'error'
259 >>> assert second('abcd')({'message': 'ok'}) == 'ok'
260
261 And now imagine that you have to change this ``3`` limit.
262 And you want to be able to set it via environment as well.
263 Ok, let's fix it with the power of ``RequiresContext.ask()``!
264
265 .. code:: python
266
267 >>> from typing_extensions import TypedDict
268 >>> class Deps(TypedDict):
269 ... message: str
270 ... limit: int # note this new field!
271
272 >>> def new_first(lg: bool) -> RequiresContext[int, Deps]:
273 ... # `deps` has `Deps` type here:
274 ... return RequiresContext(
275 ... lambda deps: deps['message'] if lg else 'err',
276 ... )
277
278 >>> def new_second(text: str) -> RequiresContext[int, Deps]:
279 ... return RequiresContext[int, Deps].ask().bind(
280 ... lambda deps: new_first(len(text) > deps.get('limit', 3)),
281 ... )
282
283 >>> assert new_second('abc')({'message': 'ok', 'limit': 2}) == 'ok'
284 >>> assert new_second('abcd')({'message': 'ok'}) == 'ok'
285 >>> assert new_second('abcd')({'message': 'ok', 'limit': 5}) == 'err'
286
287 That's how ``ask`` works.
288
289 This class contains methods that require
290 to explicitly set type annotations. Why?
291 Because it is impossible to figure out the type without them.

Callers

nothing calls this directly

Calls 1

RequiresContextClass · 0.85

Tested by

no test coverage detected