[Python-Dev] issue5578 - explanation (original) (raw)

Guido van Rossum guido at python.org
Thu Apr 2 23🔞30 CEST 2009


On Thu, Apr 2, 2009 at 2:16 PM, Chris Withers <chris at simplistix.co.uk> wrote:

R. David Murray wrote:

On Wed, 1 Apr 2009 at 13:12, Chris Withers wrote:

Guido van Rossum wrote:

 Well hold on for a minute, I remember we used to have an exec  statement in a class body in the standard library, to define some file  methods in socket.py IIRC. But why an exec?! Surely there must be some other way to do this than an exec? Maybe, but this sure is gnarly code:  s = ("def %s(self, *args): return self.sock.%s(*args)\n\n"  _"%s.doc = realsocket.%s.doc_\n")  for m in socketmethods:  exec s % (m, m, m, m)  del m, s I played around with this and managed to rewrite it as: from functools import partial from new import instancemethod def meth(name,self,*args):  return getattr(self.sock,name)(*args) for m in socketmethods:  p = partial(meth,m)  p.name = m  p.doc = getattr(realsocket,m).doc  m = instancemethod(p,None,socketobject)  setattr(socketobject,m,m) Have I missed something or is that a suitable replacement that gets rid of the exec nastiness?

That code in socket.py is much older that functools... I don't know if the dependency matters, probably not.

But anyways this is moot, the bug was only about exec in a class body nested inside a function.

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list