Can (should) this be rewritten without exec?

Terry Reedy tjreedy at udel.edu
Wed Jun 9 23:46:31 CEST 2004


"Berthold Höllmann" <bhoel at web.de> wrote in message
news:m23c541qkd.fsf at pchoel.psh...
> class X(object):
>     def a(*arg, **kw):
>         """This is test a"""
>         print "func a", arg, kw
>     a=staticmethod(a)
>     def b(*arg, **kw):
>         """This is test b"""
>         print "func b", arg, kw
>     b=staticmethod(b)
>
> def __wrapper(func, *arg, **kw):
>     func.__doc__

    print func.__doc__ #?  otherwise, this is 'pass'

>     print "start wrapper"
>     func(*arg, **kw)
>     print "done wrapper"
>
> for c in ['a', 'b']:
>     exec "%s = lambda *arg, **kw : __wrapper(X.%s, *arg, **kw)" % (c, c)
>     exec "%s.__doc__ = X.%s.__doc__" % (c, c)
> Can this be rewritten without using 'exec'?

I near as I can understand without any explanation from you, you are double
wrapping each of the staticmethods of X and binding the result to the
original name but in globals.  (This seems kind of senseless, but ;-) I
believe, without testing, the following will do something similar by using
globals() and getattr() instead of exec.

gdic = globals()
for fname in ('a', 'b'):
    fob = getattr(X, fname)
    ftem = lambda *arg, **kw : __wrapper(fob, *arg, **kw)
    ftem.__doc__ = fob.__doc__
    gdic[fname] = ftem

Terry J. Reedy







More information about the Python-list mailing list