python接收外部参数_如何从函数外部获取函数参数和值?

这是一个Python示例,模仿Perl的Inline模块功能。通过@inline装饰器,可以在函数的docstring中编写任何语言的代码,并在运行时编译为可执行的Python代码。示例中展示了如何将eval用于docstring,使得docstring中的Python代码被执行。
摘要由CSDN通过智能技术生成

我不确定这是否是你要找的,但这里有一个没有检查模块的替代品。在#!/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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值