#!/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))
虽然我不知道您为什么要这样做,但是您所描述的可以通过^{} 模块实现。这个例子和你原来的例子很接近,我可以想出。在
这应该输出
True
。在请记住,这假定传递给
f2
的任何此类函数的参数和docstring有很多事情,其中最重要的一点是所检查的函数都不是恶意的或格式错误的。为什么不想正常调用函数,为什么不想更改函数?在编辑:正如Pajton所指出的,}的调用。以上代码已更新以反映这一点。在
getcallargs
在这里更合适,并删除对dict
和{我不确定这是否是你要找的,但这里有一个没有检查模块的替代品。在
相关问题 更多 >
编程相关推荐