从字符串创建函数对象

发布于 2024-11-09 15:30:15 字数 848 浏览 0 评论 0原文

问题:有没有办法在 python 中使用字符串创建函数对象


信息:我正在开发一个将数据存储在 sqlite3 服务器后端的项目。没有什么值得疯狂的。 DAL 类通常通过代码生成来完成,因为代码非常平凡。但这给了我一个想法。在 python 中,当找不到属性时,如果定义函数 __getattr__ ,它将在出错之前调用该函数。所以按照我的想法,通过解析器和逻辑树,我可以在第一次调用时动态生成我需要的代码,然后将函数对象保存为本地属性。例如:

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

我尝试过compile函数,但是exec和eval在完成这种壮举方面还远远不能令人满意。我需要一些允许多行功能的东西。除了不涉及将其写入磁盘的方法之外,还有其他方法可以做到这一点吗?我再次尝试动态创建一个函数对象

PS:是的,我知道这存在可怕的安全性和稳定性问题。是的,我知道这是一种非常低效的方法。我关心吗?不。这是一个概念证明。 “Python 可以做到这一点吗?它可以动态创建函数对象吗?”是我想知道的,而不是一些更好的选择。 (尽管在回答了手头的问题后,可以随意选择更好的替代方案)

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


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

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.: 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

生生漫 2024-11-16 15:30:15

以下代码将您在字符串中定义的符号放入字典 d 中:

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

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

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

现在 d['f'] 是一个函数对象,它是动态绑定到d['a']。当您更改 d['a'] 时,您会更改 d['f']() 的输出。

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

d = {}
exec "def f(x): return x" in 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

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']().

嗼ふ静 2024-11-16 15:30:15

你不能做这样的事情吗?

>>> def func_builder(name):
...  def f():
...   # multiline code here, using name, and using the logic you have
...   return name
...  return f
... 
>>> func_builder("ciao")()
'ciao'

基本上,组装一个真正的函数,而不是组装一个字符串,然后尝试将其编译成一个函数。

can't you do something like this?

>>> def func_builder(name):
...  def f():
...   # multiline code here, using name, and using the logic you have
...   return name
...  return f
... 
>>> func_builder("ciao")()
'ciao'

basically, assemble a real function instead of assembling a string and then trying to compile that into a function.

韬韬不绝 2024-11-16 15:30:15

如果它只是概念上的证明,那么 eval 和 exec 就可以了,您也可以使用 pickle 字符串、yaml 字符串以及您决定为其编写构造函数的任何其他内容来完成此操作。

If it is simply proof on concept then eval and exec are fine, you can also do this with pickle strings, yaml strings and anything else you decide to write a constructor for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文