bear-utils 0.8.19__py3-none-any.whl → 0.8.20__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ def dispatch_event(name: str, *args, **kwargs) -> Any | None:
50
50
  results: list[Any] = []
51
51
  for func in _event_registry.get(name, []):
52
52
  if is_async_function(func):
53
- result: Any = asyncio.run(func(*args, **kwargs))
53
+ result: Any = asyncio.run(func(*args, **kwargs)) # FIXME: This will crash if called from an async context
54
54
  else:
55
55
  result: Any = func(*args, **kwargs)
56
56
  results.append(result)
@@ -1,6 +1,7 @@
1
1
  import asyncio
2
- from asyncio import AbstractEventLoop, get_event_loop
2
+ from asyncio import AbstractEventLoop
3
3
  from collections.abc import Callable
4
+ from contextlib import suppress
4
5
  import inspect
5
6
 
6
7
 
@@ -17,11 +18,15 @@ def is_async_function(func: Callable) -> bool:
17
18
 
18
19
 
19
20
  def in_async_loop() -> bool:
20
- """Check if the current context is already in an async loop."""
21
- try:
22
- return get_event_loop().is_running()
23
- except RuntimeError:
24
- return False
21
+ """Check if the current context is already in an async loop.
22
+
23
+ Returns:
24
+ bool: True if an async loop is running, False otherwise.
25
+ """
26
+ loop: AbstractEventLoop | None = None
27
+ with suppress(RuntimeError):
28
+ loop = asyncio.get_running_loop()
29
+ return loop.is_running() if loop else False
25
30
 
26
31
 
27
32
  def gimmie_async_loop() -> AbstractEventLoop:
@@ -2,7 +2,6 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import asyncio
6
5
  from collections.abc import Callable
7
6
  import json
8
7
  from subprocess import CompletedProcess
@@ -251,19 +250,19 @@ class FunctionResponse(BaseModel):
251
250
  ) -> Self:
252
251
  """Append additional content to the existing content."""
253
252
  try:
254
- if isinstance(content, FunctionResponse | CompletedProcess | str | list) and isinstance(
255
- error, (str | list)
256
- ):
257
- match content:
258
- case FunctionResponse():
259
- self._handle_function_response(func_response=content)
260
- case CompletedProcess():
261
- self._handle_completed_process(result=content)
262
- case str() | list() if content:
263
- self._add_content(content=content)
264
- if isinstance(error, (str | list)):
265
- self._add_error(error=error)
266
- if returncode is not None:
253
+ if content is not None:
254
+ if isinstance(content, FunctionResponse):
255
+ self._handle_function_response(func_response=content)
256
+ self.number_of_tasks += 1
257
+ elif isinstance(content, CompletedProcess):
258
+ self._handle_completed_process(result=content)
259
+ self.number_of_tasks += 1
260
+ elif isinstance(content, (str | list)) and content:
261
+ self._add_content(content=content)
262
+ self.number_of_tasks += 1
263
+ if error is not None and isinstance(error, (str | list)):
264
+ self._add_error(error=error)
265
+ if isinstance(returncode, int):
267
266
  self.returncode = returncode
268
267
  if isinstance(extra, dict):
269
268
  self.extra.update(extra)
@@ -283,10 +282,12 @@ class FunctionResponse(BaseModel):
283
282
 
284
283
  async def loop_logging(messages: list[str], func: Callable) -> None:
285
284
  for msg in messages:
285
+ if msg == "":
286
+ continue
286
287
  if is_async_function(func):
287
- await func(f"{self.name}: {msg}" if self.name else msg)
288
+ await func(f"{msg}")
288
289
  else:
289
- func(f"{self.name}: {msg}" if self.name else msg)
290
+ func(f"{msg}")
290
291
 
291
292
  async def _log_messages(
292
293
  content: str | list[str], error: str | list[str], info_func: Callable, error_func: Callable
@@ -375,39 +376,3 @@ def fail(
375
376
  ) -> FunctionResponse:
376
377
  """Create a failed FunctionResponse."""
377
378
  return FunctionResponse().fail(content=content, error=error, returncode=returncode, **kwargs)
378
-
379
-
380
- async def testing_already_in_loop() -> None:
381
- """Test function to check if already in an event loop."""
382
- # from rich import inspect
383
-
384
- response = FunctionResponse(name="example_function", logger=SimpleLogger())
385
- try:
386
- response.add(content=["Test content", "test 1234"], error="Test error", log_output=True)
387
- response.done(to_dict=True)
388
- except RuntimeError as e:
389
- print(f"Already in an event loop: {e}")
390
- else:
391
- print("Successfully added content and error without issues.")
392
- # inspect(response)
393
-
394
-
395
- def testing_not_in_loop() -> None:
396
- """Test function to check if not in an event loop."""
397
- response = FunctionResponse(name="example_function", logger=SimpleLogger())
398
- try:
399
- response.add(content=["Test content", "test 1234"], error="Test error", log_output=True)
400
- response.done(to_dict=True)
401
- except RuntimeError as e:
402
- print(f"Not in an event loop: {e}")
403
- else:
404
- print("Successfully added content and error without issues.")
405
-
406
-
407
- if __name__ == "__main__":
408
- # Example usage
409
-
410
- from bear_utils.logger_manager import SimpleLogger
411
-
412
- asyncio.run(testing_already_in_loop())
413
- testing_not_in_loop()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bear-utils
3
- Version: 0.8.19
3
+ Version: 0.8.20
4
4
  Summary: Various utilities for Bear programmers, including a rich logging utility, a disk cache, and a SQLite database wrapper amongst other things.
5
5
  Author-email: chaz <bright.lid5647@fastmail.com>
6
6
  Requires-Python: >=3.12
@@ -22,7 +22,7 @@ Requires-Dist: toml>=0.10.2
22
22
  Requires-Dist: uvicorn>=0.35.0
23
23
  Description-Content-Type: text/markdown
24
24
 
25
- # Bear Utils v# Bear Utils v0.8.19
25
+ # Bear Utils v# Bear Utils v0.8.20
26
26
 
27
27
  Personal set of tools and utilities for Python projects, focusing on modularity and ease of use. This library includes components for caching, database management, logging, time handling, file operations, CLI prompts, image processing, clipboard interaction, gradient utilities, event systems, and async helpers.
28
28
 
@@ -31,13 +31,13 @@ bear_utils/database/__init__.py,sha256=dS_HHJKESpsI6BFDLVx055o0GCJV9CMYOQVuHs7Ef
31
31
  bear_utils/database/_db_manager.py,sha256=rW4yq6arMF7UbgKrA7C2Wi37O-byqzae39tIZixfRZk,3977
32
32
  bear_utils/events/__init__.py,sha256=EFqmuzhaEYK9kjkGlrM7bjdjPwFEDbKn6RjJKfIBEJY,414
33
33
  bear_utils/events/events_class.py,sha256=vPDjWrbut8L3TFn7byyYFZpWYM5ADIqtW2Aeh-qtKfQ,1632
34
- bear_utils/events/events_module.py,sha256=rv9NoCDFOaYY70EilrImG9ug90n_wpDBDz4XvxUYqdE,2291
34
+ bear_utils/events/events_module.py,sha256=DkQsDZ5WzM1MH1Msg7mRny40a17Jl31CXbpw4-pICxc,2349
35
35
  bear_utils/extras/__init__.py,sha256=szflSapj7aGFc2j5sTitQFccXu-6_UdGG-eYuv6zVJI,607
36
- bear_utils/extras/_async_helpers.py,sha256=QBB9k2H8MBqcpkrSQv1sVz1c8M0h_J0RjTShoIJOMls,967
36
+ bear_utils/extras/_async_helpers.py,sha256=JNzUferzvTf98ocGyHE1jTzeI0_PzskRXwwYsx743Pw,1132
37
37
  bear_utils/extras/_tools.py,sha256=-rOH_-0pRd7_-o_l2QqByYBB2yhbXcTC8fuQf4Sx-eg,7671
38
38
  bear_utils/extras/platform_utils.py,sha256=Ai7ow7S-_cKb5zFwFh8dkC8xmbMJFy-0_-w3NCERdEw,1362
39
39
  bear_utils/extras/responses/__init__.py,sha256=XbE4VKemrKRwx9E5jqy__OiM_AAjA58ebnqQ2hytnT0,225
40
- bear_utils/extras/responses/function_response.py,sha256=eCfw_1oWhld8c_GdHSqLiA35oYr8k8asf-XT_baOohM,16508
40
+ bear_utils/extras/responses/function_response.py,sha256=yzZCBAIvjJbq1jBTU9X31FTc5xD_dIBSE0kuFa5YKq4,15333
41
41
  bear_utils/extras/wrappers/__init__.py,sha256=crh4sKOLvuhNMVX5bJYjCFWtXtH7G47UgNPOHq3HXTk,43
42
42
  bear_utils/extras/wrappers/add_methods.py,sha256=z2XZG2ZoYOB1MaGiLli4NRyyTeRgBy7tuYsiy8mTa9s,4422
43
43
  bear_utils/files/__init__.py,sha256=mIdnFSXoDE64ElM43bN2m6KuafURnN82ki0pdqN8q2o,201
@@ -86,6 +86,6 @@ bear_utils/monitoring/__init__.py,sha256=9DKNIWTp_voLnaWgiP-wJ-o_N0hYixo-MzjUmg8
86
86
  bear_utils/monitoring/_common.py,sha256=LYQFxgTP9fk0cH71IQTuGwBYYPWCqHP_mMRNecoD76M,657
87
87
  bear_utils/monitoring/host_monitor.py,sha256=e0TYRJw9iDj5Ga6y3ck1TBFEeH42Cax5mQYaNU8yams,13241
88
88
  bear_utils/time/__init__.py,sha256=VctjJG17SyEHAFXytI1sZrOrq7zm3hVenIDOJFdaMN0,1424
89
- bear_utils-0.8.19.dist-info/METADATA,sha256=LMfD9XfFOivtdM_om_ozrLP0FSPfAEdOT_Izo7tiafY,8699
90
- bear_utils-0.8.19.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
91
- bear_utils-0.8.19.dist-info/RECORD,,
89
+ bear_utils-0.8.20.dist-info/METADATA,sha256=rZtYas4NVnomUcpDMN2q1IhAa02z4KgSWreISVKvanU,8699
90
+ bear_utils-0.8.20.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
91
+ bear_utils-0.8.20.dist-info/RECORD,,