Note that there are some explanatory texts on larger screens.

plurals
  1. POpython: How do I dynamically create bound methods from user supplied source code?
    primarykey
    data
    text
    <p>I would like to construct a class in python that supports dynamic updating of methods from user supplied source code.</p> <p>Instances of class <code>Agent</code> have a method <code>go</code>. At the time an instance is constructed, its <code>.go()</code> method does nothing. For example, if we do <code>a=Agent()</code>, and then <code>a.go()</code> we should get a <code>NotImplementedError</code> or something like that. The user then should be able to interactively define <code>a.go()</code> by supplying source code. A simple source code example would be</p> <p>mySourceString = <code>"print('I learned how to go!')"</code></p> <p>which would be injected into <code>a</code> like this <code>a.update(mySourceString)</code></p> <p>Further invokations of <code>a.go()</code> would then result in <code>"I learned how to go!"</code> being printed to the screen.</p> <p>I have partially figured out how to do this with the following code:</p> <pre><code>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) </code></pre> <p>QUESTIONS</p> <ol> <li>Is this implementation sensible?</li> <li>Will this implementation incur unexpected scope issues?</li> <li>Is there an obvious way to sandbox the user supplied code to prevent it from touching external objects? I can think of ways to do this by supplying sets of allowed external objects, but this seems not pythonic.</li> </ol> <p>Possibly useful SO posts</p> <ol> <li><a href="https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python">What's the difference between eval, exec, and compile in Python?</a></li> <li><a href="https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object">Adding a Method to an Existing Object</a></li> </ol> <p>(I am working in python 2.6)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload