Programmatically create function specification

后端 未结 3 752
礼貌的吻别
礼貌的吻别 2021-02-04 01:46

For my own entertainment, I was wondering how to achieve the following:

functionA = make_fun([\'paramA\', \'paramB\'])
functionB = make_fun([\'arg1\', \'arg2\',          


        
3条回答
  •  爱一瞬间的悲伤
    2021-02-04 02:06

    You can use exec to construct the function object from a string containing Python code:

    def make_fun(parameters):
        exec("def f_make_fun({}): pass".format(', '.join(parameters)))
        return locals()['f_make_fun']
    

    Example:

    >>> f = make_fun(['a', 'b'])
    >>> import inspect
    >>> print(inspect.signature(f).parameters)
    OrderedDict([('a', ), ('b', )])
    

    If you want more functionality (e.g., default argument values), it's a matter of adapting the string that contains the code and having it represent the desired function signature.

    Disclaimer: as pointed out below it's important that you verify the contents of parameters and that the resulting Python code string is safe to pass to exec. You should construct parameters yourself or put restrictions in place to prevent the user from constructing a malicious value for parameters.

提交回复
热议问题