以编程方式创建函数规范

27

出于自己的娱乐,我在思考如何实现以下目标:

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

等同于

def functionA(paramA, paramB):
    print(paramA)
    print(paramB)

def functionB(arg1, arg2, arg3):
    print(arg1)
    print(arg2)
    print(arg3) 

这意味着需要遵循以下行为:

functionA(3, paramB=1)       # Works
functionA(3, 2, 1)           # Fails
functionB(0)                 # Fails

这个问题的重点在于变量argspec - 我可以使用通常的装饰器技巧来创建函数体。

对于那些感兴趣的人,我正在尝试编写类似以下代码的程序。再次强调难点在于生成具有程序化参数的__init__方法-类的其余部分似乎可以使用装饰器或元类进行简单实现。

class MyClass:
    def __init__(self, paramA=None, paramB=None):
        self._attr = ['paramA', 'paramB']
        for a in self._attr:
            self.__setattr__(a, None)

    def __str__(self):
        return str({k:v for (k,v) in self.__dict__.items() if k in self._attributes})

2
我并不是要传递可变数量的参数。我想要以程序方式创建任何形式的函数规范。装饰器和元类可以用于以编程方式创建函数和类,但我遇到的每个示例都将函数规范硬编码了。 - Zero
3个回答

15
您可以使用exec函数来从包含Python代码的字符串构建函数对象:
def make_fun(parameters):
    exec("def f_make_fun({}): pass".format(', '.join(parameters)))
    return locals()['f_make_fun']

示例:

>>> f = make_fun(['a', 'b'])
>>> import inspect
>>> print(inspect.signature(f).parameters)
OrderedDict([('a', <Parameter at 0x1024297e0 'a'>), ('b', <Parameter at 0x102429948 'b'>)])

如果你想要更多的功能(例如默认参数值),那就需要调整包含代码的字符串,并使其表示所需的函数签名。

免责声明:如下所述,重要的是验证parameters的内容以及生成的Python代码字符串是否安全可传递给exec。你应该自行构建parameters或设置限制,以防止用户构造恶意parameters值。


不错,只要记住不要在用户输入中使用它,否则有人可以像这样使用它:make_fun(['):\n import sys\n sys.exit()\n if (True'])()并让你的代码崩溃 :P - Maciej Gol
@kroolik:是的,那是个好观点。我添加了免责声明以确保安全。确保构建的代码可以安全地执行是非常重要的。 - Simeon Visser
由于这是最简单的解决方案,也是确保与手动定义函数完全相同行为的唯一方法,所以被接受。 - Zero

6

使用类的一种可能解决方案:

def make_fun(args_list):
    args_list = args_list[:]

    class MyFunc(object):
        def __call__(self, *args, **kwargs):
            if len(args) > len(args_list):
                raise ValueError('Too many arguments passed.')

            # At this point all positional arguments are fine.
            for arg in args_list[len(args):]:
                if arg not in kwargs:
                    raise ValueError('Missing value for argument {}.'.format(arg))

            # At this point, all arguments have been passed either as
            # positional or keyword.
            if len(args_list) - len(args) != len(kwargs):
                raise ValueError('Too many arguments passed.')

            for arg in args:
                print(arg)

            for arg in args_list[len(args):]:
                print(kwargs[arg])

    return MyFunc()

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

functionA(3, paramB=1)       # Works
try:
    functionA(3, 2, 1)           # Fails
except ValueError as e:
    print(e)

try:
    functionB(0)                 # Fails
except ValueError as e:
    print(e)

try:
    functionB(arg1=1, arg2=2, arg3=3, paramC=1)                 # Fails
except ValueError as e:
    print(e)

1
我喜欢这种处理*arg和**kwarg的通用方法,但在我看来,它过于复杂化了我正在寻找的用例。虽然...构建和执行字符串似乎有点笨拙! - Zero

5

以下是使用functools.wrap的另一种方法,至少在Python 3中保留了签名和文档字符串。诀窍是在从未被调用的虚拟函数中创建签名和文档。以下是几个示例。

基本示例

import functools

def wrapper(f):
    @functools.wraps(f)
    def template(common_exposed_arg, *other_args, common_exposed_kwarg=None, **other_kwargs):
        print("\ninside template.")
        print("common_exposed_arg: ", common_exposed_arg, ", common_exposed_kwarg: ", common_exposed_kwarg)
        print("other_args: ", other_args, ",  other_kwargs: ", other_kwargs)
    return template

@wrapper
def exposed_func_1(common_exposed_arg, other_exposed_arg, common_exposed_kwarg=None):
    """exposed_func_1 docstring: this dummy function exposes the right signature"""
    print("this won't get printed")

@wrapper
def exposed_func_2(common_exposed_arg, common_exposed_kwarg=None, other_exposed_kwarg=None):
    """exposed_func_2 docstring"""
    pass

exposed_func_1(10, -1, common_exposed_kwarg='one')
exposed_func_2(20, common_exposed_kwarg='two', other_exposed_kwarg='done')
print("\n" + exposed_func_1.__name__)
print(exposed_func_1.__doc__)

结果是:

>> inside template.
>> common_exposed_arg:  10 , common_exposed_kwarg:  one
>> other_args:  (-1,) ,  other_kwargs:  {}
>>  
>> inside template.
>> common_exposed_arg:  20 , common_exposed_kwarg:  two
>> other_args:  () ,  other_kwargs:  {'other_exposed_kwarg': 'done'}
>>  
>> exposed_func_1
>> exposed_func_1 docstring: this dummy function exposes the right signature

调用inspect.signature(exposed_func_1).parameters可以返回所需的签名。但是,使用inspect.getfullargspec(exposed_func_1)仍然返回template的签名。至少,如果您在template的定义中放置任何所有要创建的函数的公共参数,那么这些参数将出现。
如果由于某种原因这是个坏主意,请告诉我!
更复杂的例子
您可以比这更复杂,通过在更多包装器中添加更多层,并在内部函数中定义更多不同的行为:
import functools

def wrapper(inner_func, outer_arg, outer_kwarg=None):
    def wrapped_func(f):
        @functools.wraps(f)
        def template(common_exposed_arg, *other_args, common_exposed_kwarg=None, **other_kwargs):
            print("\nstart of template.")
            print("outer_arg: ", outer_arg, " outer_kwarg: ", outer_kwarg)
            inner_arg = outer_arg * 10 + common_exposed_arg
            inner_func(inner_arg, *other_args, common_exposed_kwarg=common_exposed_kwarg, **other_kwargs)
            print("template done")
        return template
    return wrapped_func

# Build two examples.
def inner_fcn_1(hidden_arg, exposed_arg, common_exposed_kwarg=None):
    print("inner_fcn, hidden_arg: ", hidden_arg, ", exposed_arg: ", exposed_arg, ", common_exposed_kwarg: ", common_exposed_kwarg)

def inner_fcn_2(hidden_arg, common_exposed_kwarg=None, other_exposed_kwarg=None):
    print("inner_fcn_2, hidden_arg: ", hidden_arg, ", common_exposed_kwarg: ", common_exposed_kwarg, ", other_exposed_kwarg: ", other_exposed_kwarg)

@wrapper(inner_fcn_1, 1)
def exposed_function_1(common_exposed_arg, other_exposed_arg, common_exposed_kwarg=None):
    """exposed_function_1 docstring: this dummy function exposes the right signature """
    print("this won't get printed")

@wrapper(inner_fcn_2, 2, outer_kwarg="outer")
def exposed_function_2(common_exposed_arg, common_exposed_kwarg=None, other_exposed_kwarg=None):
    """ exposed_2 doc """
    pass

这段话有点啰嗦,但是它想表达的是,在使用这种方法来创建函数时,你(程序员)的动态输入有很大的灵活性,所以在使用功能的用户暴露的输入处也同样具有灵活性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接