python:如何从用户提供的源代码动态创建绑定方法?

2024-09-29 23:30:20 发布

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

我想用python构造一个类,它支持从用户提供的源代码中动态更新方法。在

Agent的实例有一个方法go。在构造实例时,它的.go()方法什么也不做。例如,如果我们做a=Agent(),然后a.go(),我们应该得到NotImplementedError或类似的东西。然后用户应该能够通过提供源代码来交互式地定义a.go()。一个简单的源代码示例是

mySourceString="print('I learned how to go!')"

会像这样被注入aa.update(mySourceString)

进一步调用a.go()将导致"I learned how to go!"被打印到屏幕上。在

我已经用下面的代码部分地解决了这个问题:

import types

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class NotImplementedError(Error):
    pass

class Agent(object):
    def go(self):
        raise NotImplementedError()

    def update(self,codeString):
        #Indent each line of user supplied code
        codeString = codeString.replace('\n','\n    ')
        #Turn code into a function called func
        exec "def func(self):\n"+'    '+codeString
        #Make func a bound method on this instance
        self.go = types.MethodType(func, self)

问题

  1. 这一实施是否明智?在
  2. 此实现是否会引发意外的范围问题?在
  3. 有没有一个明显的方法可以沙箱用户提供的代码,以防止它接触外部对象?我可以通过提供一组允许的外部对象来实现这一点,但这似乎不是python式的。在

可能有用的SO帖子

  1. What's the difference between eval, exec, and compile in Python?
  2. Adding a Method to an Existing Object

(我在Python2.6中工作)


Tags: to实例方法用户selfgo源代码def

热门问题