如何从函数外部获取函数参数和值?

2024-05-02 10:49:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经搜索了一点,试图找出这一点,但没有得到一个解决方案,我正寻找。在

这是我的用例:

  • 我想根据f/m的参数和值从函数/方法doc字符串中计算表达式,但是要从函数外部(当被调用时,但是在函数的执行之外)
  • 我不能静态地更改正在评估的源代码(不能编写新的功能),但可以接受动态更改(即包装函数或在运行时添加属性)
  • 我更喜欢使用标准库中的工具,但如果外部库能让任务轻松完成,我愿意尝试外部库

下面是一个简单的例子来说明我要做的事情:

def f1(a,b):
    """a==b"""
    pass

def f2(f):
    f_locals = "get f's args and values before f is executed"
    return eval(f.__doc__,None,f_locals)

>>> f2(f1(2,2))

Tags: 方法函数字符串功能参数doc源代码表达式
2条回答

虽然我不知道您为什么要这样做,但是您所描述的可以通过^{}模块实现。这个例子和你原来的例子很接近,我可以想出。在

from inspect import getcallargs
def f1(a,b):
   """a==b"""
   pass

def f2(f, *f_args, **f_kwargs):
    f_callargs = getcallargs(f, *f_args, **f_kwargs)
    return eval(f.__doc__, None, f_callargs)

f2(f1, 2, 2)

这应该输出True。在

请记住,这假定传递给f2的任何此类函数的参数和docstring有很多事情,其中最重要的一点是所检查的函数都不是恶意的或格式错误的。为什么不想正常调用函数,为什么不想更改函数?在

编辑:正如Pajton所指出的,getcallargs在这里更合适,并删除对dict和{}的调用。以上代码已更新以反映这一点。在

我不确定这是否是你要找的,但这里有一个没有检查模块的替代品。在

#!/usr/bin/python
# -*- coding: utf-8-unix -*-
"""
This is a sample implementation of Inline.pm (Perl) in Python.

Using @inline decorator, it is now possible to write any code
in any language in docstring, and let it compile down to executable
Python code at runtime.

For this specific example, it simply evals input docstring, so
code in docstring must be in Python as well.
"""

# Language compiler for MyLang
class MyLang:
    @classmethod
    def compile(self, docstring):
        # For this example, this simply generates code that
        # evals docstring.
        def testfunc(*arg, **kw):
            return eval(docstring, None, kw)
        return testfunc

# @inline decorator
def inline(lang):
    def decorate(func):
        parm = func.__code__.co_varnames[0:func.__code__.co_argcount]
        fgen = lang.compile(func.__doc__)
        def wrap(*arg, **kw):
            # turn all args into keyword-args
            kw.update(dict(zip(parm, arg)))
            return fgen(**kw)
        return wrap
    return decorate

@inline(MyLang)
def myadd(a, b):
    """a + b"""

print(myadd(1, 9))
print(myadd(b = 8, a = 2))
print(myadd(a = 3, b = 7))

相关问题 更多 >