Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!feeder.news-service.com!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'args': 0.05; 'attributes': 0.05; 'instance': 0.05; '#if': 0.07; 'attribute': 0.07; 'method,': 0.07; 'override': 0.07; 'reference:': 0.07; 'slices': 0.07; 'attribute.': 0.09; 'decorator': 0.09; 'modifies': 0.09; 'reflected': 0.09; 'subclass': 0.09; 'def': 0.15; '*args)': 0.16; '*args):': 0.16; '@property': 0.16; 'attribute,': 0.16; 'attributes.': 0.16; 'instances,': 0.16; 'reconstructs': 0.16; 'subclassing': 0.16; 'this:': 0.16; 'arguments': 0.18; 'modified': 0.18; "haven't": 0.20; 'wrote': 0.20; 'sound': 0.21; 'sender:addr:gmail.com': 0.25; 'says': 0.25; 'code': 0.25; 'function': 0.27; 'skip:[ 10': 0.27; 'fact': 0.27; 'alternatives': 0.29; 'work:': 0.29; 'skip:( 20': 0.29; 'example': 0.30; '"why': 0.30; 'calculated': 0.30; 'class': 0.30; 'list': 0.32; 'represents': 0.32; 'to:addr:python-list': 0.33; 'calling': 0.33; 'on,': 0.34; 'someone': 0.34; 'test': 0.34; 'like:': 0.34; 'apply': 0.35; 'reference': 0.35; 'charset:us-ascii': 0.36; 'put': 0.37; 'but': 0.37; 'received:google.com': 0.38; 'initially': 0.39; 'header:Mime-Version:1': 0.39; 'else': 0.39; 'to:addr:python.org': 0.39; 'received:74.125': 0.39; 'skip:d 20': 0.39; "i'd": 0.40; 'subject:from': 0.40; 'target': 0.61; 'kind': 0.61; 'header :Message-Id:1': 0.61; 'john': 0.62; 'comments,': 0.64; 'making': 0.67; 'subject:without': 0.67; 'care': 0.71; 'subject:class': 0.84; 'contents,': 0.91; 'received:home': 0.91; 'increases': 0.93; 'inheritance,': 0.93 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=sender:date:from:to:subject:message-id:x-mailer:mime-version :content-type:content-transfer-encoding; bh=9egKAz5C3gptDfZ1tASnH5Js33ekA0WYv/bj2FJ7E/0=; b=GWiPRAF0w8f3A0ZqtZT6MGvmA45AaTR1OZ/8JVt4XwrzVqjAeEX4kgRH9hERyH9uu6 G5nw0wFfCx4OdwJOQfO08zJcDpmTbmBY/VFKEzSm2Np1ZmFs2ZlBMcMFsax7Yp8t1izv O1EpJdonezGLtlrSNhYtHIPsarKL0BL6xnCag= Sender: "John O'Hagan" Date: Mon, 22 Aug 2011 15:04:45 +1000 From: John O'Hagan To: python-list@python.org Subject: Adding modified methods from another class without subclassing X-Mailer: Sylpheed 3.2.0beta1 (GTK+ 2.24.4; x86_64-pc-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 78 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1313989495 news.xs4all.nl 23979 [2001:888:2000:d::a6]:58188 X-Complaints-To: abuse@xs4all.nl Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:11993 I have a class like this: class MySeq(): def __init__(self, *seq, c=12): self.__c = c self.__pc = sorted(set([i % __c for i in seq])) self.order = ([[self.__pc.index(i % __c), i // __c] for i in seq]) #other calculated attributes @property def pitches(self): return [self.__pc[i[0]] + i[1] * self.__c for i in self.order] #other methods The "pitches" attribute initially reconstructs the "seq" arguments but can be modified by writing to the "order" attribute. The "pitches" attribute represents the instances and as such I found myself adding a lot of methods like: def __getitem__(self, index): return self.pitches[index] def __len__(self): return len(self.pitches) def __iter__(self): return iter(self.pitches) def __repr__(self): return str(self.pitches) and so on, and calling a lot of list methods on the "pitches" attribute of MySeq instances elsewhere. I thought of making MySeq a subclass of list with "pitches" as its contents, but then I would have had to override a lot of methods case-by-case, for example to ensure that any alterations to "pitches" were reflected in the other calculated attributes. So I wrote this function which takes a method, modifies it to apply to an instance attribute, and takes care of any quirks: def listmeth_to_attribute(meth, attr): def new_meth(inst, *args): #ensure comparison operators work: args = [getattr(i, attr) if isinstance(i, inst.__class__) else i for i in args] reference = getattr(inst, attr) test = reference[:] result = meth(test, *args) #ensure instance is reinitialised #if attribute has been changed: if test != reference: inst.__init__(*test) #ensure slices are of same class if isinstance(result, meth.__objclass__): result = inst.__class__(*result) return result return new_meth and this decorator to apply this function to all the list methods and add them to MySeq: def add_mod_methods(source_cls, modfunc, modfunc_args, *overrides): """Overides = any methods in target to override from source""" def decorator(target_cls): for name, meth in vars(source_cls).items(): if name not in dir(target_cls) or name in overrides: setattr(target_cls, name, modfunc(meth, *modfunc_args)) return target_cls return decorator a kind of DIY single inheritance, used like this: @add_mod_methods(list, listmeth_to_attribute, ('pitches',), '__repr__') class MySeq(): ..... Now I can call list methods transparently on MySeq instances, like subclassing but without all the overriding. If this works it will simplify a lot of code in my project. But the fact that I haven't seen this approach before increases the likelihood it may not be a good idea. I can almost hear the screams of "No, don't do that!" or the sound of me slapping my forehead when someone says "Why don't you just...". So before I put it in, I'd appreciate any comments, warnings, criticisms, alternatives etc.. Regards, John