[Misc] Clean up more utils (#27567)

Signed-off-by: DarkLight1337 <tlleungac@connect.ust.hk>
This commit is contained in:
Cyrus Leung
2025-10-27 15:30:38 +00:00
committed by GitHub
parent 3b96f85c36
commit 6ebffafbb6
24 changed files with 282 additions and 315 deletions
+28
View File
@@ -5,6 +5,7 @@ import dataclasses
import importlib
import pickle
from collections.abc import Callable, Sequence
from functools import partial
from inspect import isclass
from types import FunctionType
from typing import Any, TypeAlias
@@ -429,3 +430,30 @@ class MsgpackDecoder:
return cloudpickle.loads(data)
raise NotImplementedError(f"Extension type code {code} is not supported")
def run_method(
obj: Any,
method: str | bytes | Callable,
args: tuple[Any, ...],
kwargs: dict[str, Any],
) -> Any:
"""
Run a method of an object with the given arguments and keyword arguments.
If the method is string, it will be converted to a method using getattr.
If the method is serialized bytes and will be deserialized using
cloudpickle.
If the method is a callable, it will be called directly.
"""
if isinstance(method, bytes):
func = partial(cloudpickle.loads(method), obj)
elif isinstance(method, str):
try:
func = getattr(obj, method)
except AttributeError:
raise NotImplementedError(
f"Method {method!r} is not implemented."
) from None
else:
func = partial(method, obj) # type: ignore
return func(*args, **kwargs)