You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于字典生成带Python 3类型注解且可正常调用的函数?

Solution: Create Custom Signatures with the inspect Module

The key here is to manually build the desired function signature using the inspect module's Signature and Parameter classes, then attach it to your generated function via the special __signature__ attribute. This approach avoids AST manipulation and relies on stable standard library features.

Here's the implementation:

from inspect import Signature, Parameter
from typing import Dict, Any, Callable

def gen_fn(args: Dict[str, Any]) -> Callable:
    # Convert input dict into inspect Parameter objects
    parameters = [
        Parameter(
            name=param_name,
            kind=Parameter.POSITIONAL_OR_KEYWORD,
            annotation=param_type
        )
        for param_name, param_type in args.items()
    ]
    
    # Create the custom signature from our parameters
    custom_signature = Signature(parameters)
    
    # Define the generated function to accept any args/kwargs (prevents TypeError)
    def new_fn(*args, **kwargs):
        # Add your own logic here if you need to process the arguments
        pass
    
    # Attach the custom signature to the function
    new_fn.__signature__ = custom_signature
    
    return new_fn

How It Works:

  1. Parameter Construction: Each entry in your input dictionary is turned into a Parameter object, configured as a standard positional-or-keyword parameter (the most common type for function arguments).
  2. Signature Assembly: We combine these parameters into a Signature object that exactly matches what you need (e.g., (a:int) for the input {'a': int}).
  3. Flexible Function Definition: The new_fn accepts *args and **kwargs to ensure any valid calls matching the custom signature won't throw a TypeError.
  4. Signature Binding: By setting new_fn.__signature__, we tell the inspect module to use our custom signature instead of inferring it from the function's actual parameter list.

Testing the Solution:

import inspect

# Generate the function
my_fn = gen_fn({'a': int})

# Verify the signature
print(inspect.signature(my_fn))  # Output: <Signature (a:int)>

# Call with valid arguments (no TypeError)
my_fn(a=42)
my_fn(42)  # Works too, since the parameter accepts positional input

This method is stable across Python versions (the inspect module's core APIs are consistent) and avoids the complexity of AST manipulation.

内容的提问来源于stack exchange,提问作者Chen Levy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:15:58