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

Chris Withers chris at simplistix.co.uk
Thu Apr 2 23:16:28 CEST 2009


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?

Chris

-- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk



More information about the Python-Dev mailing list