从字符串创建函数对象 [英] Creating a function object from a string

查看:121
本文介绍了从字符串创建函数对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:有没有办法使用字符串在Python中制作函数对象

Question: Is there a way to make a function object in python using strings?

信息:我正在一个项目中,我将数据存储在sqlite3服务器后端中。没什么可疯狂的。 DAL类通常是通过代码生成来完成的,因为代码是如此平凡。但这给了我一个主意。在python中找不到属性时,如果定义函数 __ getattr __ ,它将在错误之前调用它。因此,我通过解析器和逻辑树来计算它的方式可以动态生成第一次调用时所需的代码,然后将函数对象另存为本地属性。例如:

Info: I'm working on a project which I store data in a sqlite3 server backend. nothing to crazy about that. a DAL class is very commonly done through code generation because the code is so incredibly mundane. But that gave me an idea. In python when a attribute is not found, if you define the function __getattr__ it will call that before it errors. so the way I figure it, through a parser and a logic tree I could dynamically generate the code I need on its first call, then save the function object as a local attrib. for example:

DAL.getAll()

#getAll() not found, call __getattr__

DAL.__getattr__(self,attrib)#in this case attrib = getAll

##parser logic magic takes place here and I end up with a string for a new function

##convert string to function

DAL.getAll = newFunc

return newFunc

我已经尝试过编译功能,但是exec和eval在能够完成这种壮举方面远非令人满意。我需要允许多行功能的东西。除了不涉及将其写入磁盘以外,还有另一种方法吗?再次尝试动态创建功能对象

I've tried the compile function, but exec, and eval are far from satisfactory in terms of being able to accomplish this kind of feat. I need something that will allow multiple lines of function. Is there another way to do this besides those to that doesn't involve writing the it to disk? Again I'm trying to make a function object dynamically.

P.S .:是的,我知道这存在可怕的安全性和稳定性问题。是的,我知道这是一种极其低效的方法。我关心的?没有。这是概念的证明。 python可以这样做吗?它可以动态创建一个功能对象吗?我想知道的是这,而不是一些更高级的选择。 (尽管您已经回答了当前的问题,但是可以随意使用其他替代方法)

P.S.: Yes, I know this has horrible security and stability problems. yes, I know this is a horribly in-efficient way of doing this. do I care? no. this is a proof of concept. "Can python do this? Can it dynamically create a function object?" is what I want to know, not some superior alternative. (though feel free to tack on superior alternatives after you've answered the question at hand)

推荐答案

以下内容将符号您在字典中的字符串中定义 d

The following puts the symbols that you define in your string in the dictionary d:

d = {}
exec "def f(x): return x" in d

现在 d ['f'] 是一个函数对象。如果要在字符串的代码中使用程序中的变量,可以通过 d 发送该变量:

Now d['f'] is a function object. If you want to use variables from your program in the code in your string, you can send this via d:

d = {'a':7}
exec "def f(x): return x + a" in d

现在d ['f'] 是动态绑定到<$ c $的函数对象c> d ['a'] 。更改 d ['a'] 时,将更改 d ['f']()的输出。

Now d['f'] is a function object that is dynamically bound to d['a']. When you change d['a'], you change the output of d['f']().

这篇关于从字符串创建函数对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆