如何基于字典生成带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:
- Parameter Construction: Each entry in your input dictionary is turned into a
Parameterobject, configured as a standard positional-or-keyword parameter (the most common type for function arguments). - Signature Assembly: We combine these parameters into a
Signatureobject that exactly matches what you need (e.g.,(a:int)for the input{'a': int}). - Flexible Function Definition: The
new_fnaccepts*argsand**kwargsto ensure any valid calls matching the custom signature won't throw aTypeError. - Signature Binding: By setting
new_fn.__signature__, we tell theinspectmodule 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
相关产品推荐
相关产品推荐

