Skip to content

Commit

Permalink
Use inspect to support typeguard version being overridden
Browse files Browse the repository at this point in the history
Summary: Attempt to solve/mitigate facebook#2043

Differential Revision: D51853729
  • Loading branch information
Daniel Cohen authored and facebook-github-bot committed Dec 5, 2023
1 parent 79133c7 commit 0de28fc
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion ax/utils/common/kwargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ def get_function_default_arguments(function: Callable) -> Dict[str, Any]:
}


def version_safe_check_type(argname, value, expected_type):
"""Excecute the check_type function if it has the expected signature, otherwise
warn. This is done to support newer versions of typeguard with minimal loss
of functionality for users that have dependency conflicts"""
# Get the signature of the check_type function
sig = signature(check_type)
# Get the parameters of the check_type function
params = sig.parameters
# Check if the check_type function has the expected signature
if list(params.keys()) == ['argname', 'value', 'expected_type']:
check_type(argname, value, expected_type)
else:
logger.warning(
"You are using an unsupported version of `typeguard`. "
f"`{argname}` is not being validated."
)


# pyre-fixme[24]: Generic type `Callable` expects 2 type parameters.
def validate_kwarg_typing(typed_callables: List[Callable], **kwargs: Any) -> None:
"""Check if keywords in kwargs exist in any of the typed_callables and
Expand All @@ -82,7 +100,7 @@ def validate_kwarg_typing(typed_callables: List[Callable], **kwargs: Any) -> Non
# if the keyword is a callable, we only do shallow checks
if not (callable(kw_val) and callable(param.annotation)):
try:
check_type(kw, kw_val, param.annotation)
version_safe_check_type(kw, kw_val, param.annotation)
except TypeError:
message = (
f"`{typed_callable}` expected argument `{kw}` to be of"
Expand Down

0 comments on commit 0de28fc

Please sign in to comment.