以编程方式创建函数规范

Zer*_*ero 15 python python-3.x

更新:我不是在询问可变数量的参数.最终结果(如果可能的话)应该是一个完全按照我下面的例子定义的函数,或者至少完全按照这种方式行事 - 我在问题中添加了一些例子来试图澄清这一点.

(可能的情况是,实现这一目标的唯一方法是使用__init__然后手动处理这些并在输入与预期不完全匹配时引发适当的异常,在这种情况下,这将是一个有效的答案)

为了我自己的娱乐,我想知道如何实现以下目标:

functionA = make_fun(['paramA', 'paramB'])
functionB = make_fun(['arg1', 'arg2', 'arg3'])
Run Code Online (Sandbox Code Playgroud)

相当于

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

def functionB(arg1, arg2, arg3):
    print(arg1)
    print(arg2)
    print(arg3) 
Run Code Online (Sandbox Code Playgroud)

这意味着需要以下行为:

functionA(3, paramB=1)       # Works
functionA(3, 2, 1)           # Fails
functionB(0)                 # Fails
Run Code Online (Sandbox Code Playgroud)

问题的焦点在于变量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})
Run Code Online (Sandbox Code Playgroud)

Sim*_*ser 9

您可以使用exec从包含Python代码的字符串构造函数对象:

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

例:

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

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

免责声明:正如下面所指出的那样,重要的是要验证parameters生成的Python代码字符串的内容以及传递给它的安全性exec.您应该parameters自己构建或设置限制以防止用户构造恶意值parameters.


Mac*_*Gol 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)
Run Code Online (Sandbox Code Playgroud)


Ada*_* S. 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__)
Run Code Online (Sandbox Code Playgroud)

结果是:

>> 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
Run Code Online (Sandbox Code Playgroud)

调用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
Run Code Online (Sandbox Code Playgroud)

这有点冗长,但要点是,当使用它来创建函数时,来自您(程序员)的动态输入的位置以及公开的输入(来自函数的用户)的位置有很大的灵活性习惯了。