Skip to content

Commit

Permalink
Update get_caller_stack to accept an iterable of instances in which i…
Browse files Browse the repository at this point in the history
…t should consider their method names to be part of the local scope
  • Loading branch information
LobaDK committed Aug 23, 2024
1 parent 9d3a403 commit c764569
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
6 changes: 3 additions & 3 deletions settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def save(self) -> None:
Raises:
SaveError: If there is an error while writing the settings to the file.
"""
logger.debug(msg=f"Save requested by {get_caller_stack(instance=self)}...")
logger.debug(msg=f"Save requested by {get_caller_stack(instances=[self])}...")
settings_data: Dict[str, Any] = self._to_dict(obj=self.settings)
if self._auto_sanitize_on_save:
self.sanitize_settings()
Expand Down Expand Up @@ -273,7 +273,7 @@ def load(self) -> None:
Raises:
LoadError: If there is an error while reading the settings from the file.
"""
logger.debug(msg=f"Load requested by {get_caller_stack(instance=self)}...")
logger.debug(msg=f"Load requested by {get_caller_stack(instances=[self])}...")
with open(file=self._read_path, mode="r") as f:
try:
self.settings = self._from_dict(data=self._read(file=f))
Expand Down Expand Up @@ -343,7 +343,7 @@ def sanitize_settings(self) -> None:
"""
logger.debug(
msg=f"Sanitization requested by {get_caller_stack(instance=self)}..."
msg=f"Sanitization requested by {get_caller_stack(instances=[self])}..."
)
settings: Dict[str, Any] = self._to_dict(obj=self.settings)
default_settings: Dict[str, Any] = self._to_dict(obj=self._default_settings)
Expand Down
22 changes: 10 additions & 12 deletions settings/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from types import FrameType
from typing import Dict, Optional, overload, Tuple, TypeVar
from typing import Dict, Iterable, Optional, overload, Tuple, TypeVar, List
from pathlib import Path
from inspect import FrameInfo, stack, getmembers, currentframe

Expand Down Expand Up @@ -224,14 +224,14 @@ def filter_locals(locals_dict: Dict[str, T]) -> Dict[str, T]:
return {key: value for key, value in locals_dict.items() if not key.startswith("_")}


def get_caller_stack(instance: Optional[object] = None) -> str:
def get_caller_stack(instances: Optional[Iterable[object]] = None) -> str:
"""
Gets a stack of callers leading up to the caller of the function, if available.
Optionally, the instance of the class that called can be provided to filter out method names and potentially provide a more accurate stack of callers.
Optionally, an iterable of instances that should be considered local methods and ignored, can be provided.
Args:
instance (Optional[object]): The instance of the class that called the function. Defaults to None.
instances (Optional[Iterable[object]]): An iterable of instances that should be considered local methods and ignored.
Returns:
str: The name of the caller of the function. If no caller can be determined, returns "Unknown".
Expand All @@ -241,17 +241,15 @@ def get_caller_stack(instance: Optional[object] = None) -> str:
'run'
"""
_stack: list[FrameInfo] = stack()[:10] # Limit the stack to 10 frames.
_stack: List[FrameInfo] = stack()[:10] # Limit the stack to 10 frames.
if len(_stack) < 3:
return "Unknown"

method_names: list[str] = []
if instance:
method_names = [
method_name
for method_name, _ in getmembers(object=instance, predicate=callable)
if not method_name.startswith("__")
]
method_names: List[str] = []
for item in instances or []:
for method_name, _ in getmembers(object=item, predicate=callable):
if not method_name.startswith("__") and method_name not in method_names:
method_names.append(method_name)

frame_length: int = len(_stack) - 1
caller_stack: str = ""
Expand Down

0 comments on commit c764569

Please sign in to comment.