782. Parse a function call string and dispatch it with signature checks
Agents and simple command consoles receive calls as text, such as add(2, 3). Before running anything you must parse the text safely and check the arguments against the target function's signature.
Write call_from_string(registry, text). registry maps a name to a Python function. text should be a single call like name(1, 'a', k=[1, 2]) where every argument is a Python literal (numbers, strings, booleans, None, lists, tuples, dicts).
Return the function's result on success. Return the string 'error: parse' if the text is not a single call to a plain name with literal arguments, 'error: unknown function NAME' if the name is not in the registry, and 'error: bad arguments' if the arguments do not bind to the function's signature. Never use eval.
def call_from_string(registry, text)Example 1
Input: with registry = {'add': lambda a, b=0: a + b}, call_from_string(registry, 'add(2, b=3)')
Output: 5 and call_from_string(registry, 'add(1, 2, 3)') returns 'error: bad arguments'
Example 2
Input: registry = R, text = 'add(2, b=3)'
Output: 5
Example 3
Input: registry = R, text = 'add(1, 2, 3)'
Output: 'error: bad arguments'
Constraints
- Standard library only
(ast, inspect). - Registry functions are pure and fast.
Hint 1
Use ast.parse with mode='eval'.
Hint 2
Use ast.literal_eval on each argument node.
Hint 3
Use inspect.signature(f).bind to check before calling.
Common mistakes
- Using eval on the string.
- Calling the function and catching TypeError, which may hide errors raised inside the function.
- Allowing attribute calls like module.func.
Understand the idea
Turning text into a function call is where agents and consoles become unsafe if you are careless. eval would run anything. The safe route has three steps: parse the text into a syntax tree and check its shape (one call, plain name), convert only literal arguments with literal_eval, then check the arguments against the function's signature before calling it. For add(a, b=0), 'add(2, b=3)' binds fine and returns 5, while 'add(1, 2, 3)' fails to bind because there is one argument too many. Tool-calling agents do the same validation on JSON arguments before running a tool.