首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以编程方式创建函数规范

以编程方式创建函数规范
EN

Stack Overflow用户
提问于 2014-11-18 05:42:30
回答 3查看 9.5K关注 0票数 27

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

代码语言:javascript
复制
functionA = make_fun(['paramA', 'paramB'])
functionB = make_fun(['arg1', 'arg2', 'arg3'])

相当于

代码语言:javascript
复制
def functionA(paramA, paramB):
    print(paramA)
    print(paramB)

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

这意味着需要采取以下行为:

代码语言:javascript
复制
functionA(3, paramB=1)       # Works
functionA(3, 2, 1)           # Fails
functionB(0)                 # Fails

问题的重点是变量argspec使用常用的装饰技术来创建函数体。

对于那些感兴趣的人,我正在尝试以编程的方式创建类,如下所示。同样,困难在于生成带有编程参数的__init__方法--类的其余部分使用修饰器或元类看起来很简单。

代码语言:javascript
复制
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})
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-11-18 22:42:48

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

代码语言:javascript
复制
def make_fun(parameters):
    exec("def f_make_fun({}): pass".format(', '.join(parameters)))
    return locals()['f_make_fun']

示例:

代码语言:javascript
复制
>>> 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构造恶意值。

票数 15
EN

Stack Overflow用户

发布于 2014-11-18 22:46:41

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

代码语言:javascript
复制
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)
票数 6
EN

Stack Overflow用户

发布于 2017-01-21 00:21:39

下面是另一种使用functools.wrap的方法,它保留签名和docstring,至少在python 3中是这样的。诀窍是用从未被调用的虚拟函数创建签名和文档。以下是几个例子。

基本实例

代码语言:javascript
复制
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__)

结果是:

代码语言:javascript
复制
>> 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的定义中将所有要创建的函数的参数设置为公共参数,这些参数就会出现。

如果出于某种原因这是个坏主意,请告诉我!

更复杂的例子

通过将更多的包装器分层,并在内部函数中定义更多不同的行为,您可以变得更加复杂:

代码语言:javascript
复制
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

这有点冗长,但关键是,在使用它创建函数时,您(程序员)的动态输入有很大的灵活性,因此公开的输入(来自函数的用户)也会被使用。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26987418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档