basic language question

Alex Martelli aleax at aleax.it
Fri Sep 5 15:23:52 CEST 2003


Terry Reedy wrote:
   ...
> 'Returners' could wrap no-return mutators with functions or
> derived-class methods that do return the object, but I have never seen
> anyone post a complete module that does so for, say, all list
> mutators.

What about...:

def wrapReturning(func):
    def returningWrapper(*args, **kwds):
        func(*args, **kwds)
        return args[0]
    return returningWrapper


class metaReturner(type):
    ''' simplified metaReturner: deal with single inheritance only '''

    def __new__(mcl, className, classBases, classDict):

        # get the "real" base class, then wrap its mutators
        for base in classBases:
            if not isinstance(base, metaReturner):
                for mutator in classDict['__mutators__']:
                    classDict[mutator] = wrapReturning(getattr(base,
mutator))
                break

        # delegate the rest to built-in 'type'
        return type.__new__(mcl, className, classBases, classDict)

class Returner: __metaclass__ = metaReturner


# example usage

class returnerlist(Returner, list):
    __mutators__ = 'sort reverse append extend insert'.split()

print returnerlist('hello').extend('ciao').sort().reverse()


Alex





More information about the Python-list mailing list