diff --git a/src/python/jw/util/misc.py b/src/python/jw/util/misc.py index a5f1f8c..58a0705 100644 --- a/src/python/jw/util/misc.py +++ b/src/python/jw/util/misc.py @@ -151,6 +151,34 @@ def load_function(module_path: str, name: str) -> Any: # export mod = importlib.import_module(module_path) return getattr(mod, name) +def frame_parameters( # export + exclude_names: Iterable[str] = ['self', 'cls'], + exclude_values: Iterable[Any] = [None], +) -> dict[str, Any]: + current_frame = inspect.currentframe() + # E: Item "None" of "FrameType | None" has no attribute "f_back" [union-attr] + assert current_frame is not None + frame = current_frame.f_back + # E: Item "None" of "FrameType | None" has no attribute "f_code" [union-attr] + assert frame is not None + code = frame.f_code + names = list(code.co_varnames[:code.co_argcount + code.co_kwonlyargcount]) + index = code.co_argcount + code.co_kwonlyargcount + if code.co_flags & inspect.CO_VARARGS: + names.append(code.co_varnames[index]) + index += 1 + if code.co_flags & inspect.CO_VARKEYWORDS: + names.append(code.co_varnames[index]) + ret: dict[str, Any] = {} + for name in names: + val = frame.f_locals[name] + if val in exclude_values: + continue + if name in exclude_names: + continue + ret[name] = val + return ret + def commit_tmpfile(tmp: str, path: str) -> None: # export caller = log.get_caller_pos() if os.path.isfile(path) and filecmp.cmp(tmp, path):