extracts method to get default value of function keyword argument

This commit is contained in:
Mose Müller 2024-02-27 08:40:15 +01:00
parent 3c2f425dee
commit 7f407ae6e7

View File

@ -149,36 +149,29 @@ class Serializer:
}
@staticmethod
def _serialize_method(obj: Callable[..., Any]) -> dict[str, Any]:
obj_type = "method"
value = None
readonly = True
doc = get_attribute_doc(obj)
# Store parameters and their anotations in a dictionary
sig = inspect.signature(obj)
parameters: dict[str, dict[str, Any]] = {}
for k, v in sig.parameters.items():
default_value = v.default
def _get_default_value_of_method_arg(
obj: Callable[..., Any], arg_name: str, arg_value: inspect.Parameter
) -> Any:
default_value = arg_value.default
if default_value is None:
raise KeywordArgumentError(
f"Default value for keyword {k!r} of function {obj.__name__!r} "
f"Default value for keyword {arg_name!r} of function {obj.__name__!r} "
"cannot be 'None'."
)
if default_value is inspect.Parameter.empty:
annotation = v.annotation
annotation = arg_value.annotation
if annotation is not inspect._empty:
if annotation is None:
raise KeywordArgumentError(
f"Type hint of keyword {k!r} of function {obj.__name__!r} "
"cannot be 'None'."
f"Type hint of keyword {arg_name!r} of function "
f"{obj.__name__!r} cannot be 'None'."
)
if issubclass(annotation, u.Quantity):
raise KeywordArgumentError(
f"Keyword {k!r} of function {obj.__name__!r} needs default "
"argument. Quantity objects have no obvious default value."
f"Keyword {arg_name!r} of function {obj.__name__!r} needs "
"default argument. Quantity objects have no obvious default "
"value."
)
if annotation == str:
@ -193,18 +186,34 @@ class Serializer:
default_value = next(iter(annotation))
else:
raise KeywordArgumentError(
f"Type of keyword {k!r} of function {obj.__name__} should "
"be a simple type (str, int, float, bool, Enum, Quantity)."
f"Type of keyword {arg_name!r} of function {obj.__name__} "
"should be a simple type (str, int, float, bool, Enum, Quantity"
")."
)
else:
logger.warning(
"Keyword %a of function %a has no type hint. "
"Defaulting to float...",
k,
arg_name,
obj.__name__,
)
default_value = 0.0
return default_value
@staticmethod
def _serialize_method(obj: Callable[..., Any]) -> dict[str, Any]:
obj_type = "method"
value = None
readonly = True
doc = get_attribute_doc(obj)
frontend_render = render_in_frontend(obj)
# Store parameters and their anotations in a dictionary
sig = inspect.signature(obj)
parameters: dict[str, dict[str, Any]] = {}
for k, v in sig.parameters.items():
default_value = Serializer._get_default_value_of_method_arg(obj, k, v)
parameters[k] = dump(default_value)
return {
@ -214,7 +223,7 @@ class Serializer:
"doc": doc,
"async": inspect.iscoroutinefunction(obj),
"parameters": parameters,
"frontend_render": render_in_frontend(obj),
"frontend_render": frontend_render,
}
@staticmethod