Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12002

Re: Adding modified methods from another class without subclassing

Path csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!feeder.news-service.com!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <python-python-list@m.gmane.org>
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; 'debug': 0.03; 'args': 0.05; 'attributes': 0.05; 'instance': 0.05; 'url:bugs': 0.05; '#if': 0.07; 'attribute': 0.07; 'method,': 0.07; 'override': 0.07; 'reference:': 0.07; 'slices': 0.07; 'python': 0.08; 'attribute.': 0.09; 'decorator': 0.09; 'modifies': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:80.91.229.12': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'received:lo.gmane.org': 0.09; 'reflected': 0.09; 'subclass': 0.09; 'def': 0.15; 'library': 0.15; '*args)': 0.16; '*args):': 0.16; '@property': 0.16; 'attribute,': 0.16; 'attributes.': 0.16; 'instances,': 0.16; 'received:dip.t-dialin.net': 0.16; 'received:t-dialin.net': 0.16; 'reconstructs': 0.16; 'subclassing': 0.16; 'this:': 0.16; 'wrote:': 0.16; 'arguments': 0.18; 'modified': 0.18; "haven't": 0.20; 'wrote': 0.20; 'sound': 0.21; "doesn't": 0.22; 'says': 0.25; 'code': 0.25; 'function': 0.27; 'skip:[ 10': 0.27; 'fact': 0.27; 'alternatives': 0.29; 'work:': 0.29; 'looks': 0.29; 'skip:( 20': 0.29; 'example': 0.30; '"why': 0.30; 'calculated': 0.30; 'from:addr:web.de': 0.30; 'class': 0.30; 'list': 0.32; 'represents': 0.32; 'there': 0.33; 'to:addr:python-list': 0.33; 'calling': 0.33; 'on,': 0.34; 'someone': 0.34; 'test': 0.34; 'like:': 0.34; 'header:X -Complaints-To:1': 0.35; 'apply': 0.35; 'uses': 0.35; 'reference': 0.35; 'url:python': 0.36; 'using': 0.37; 'put': 0.37; 'but': 0.37; 'received:org': 0.38; 'url:org': 0.38; 'subject:: ': 0.39; 'initially': 0.39; 'enough': 0.39; 'header:Mime-Version:1': 0.39; 'else': 0.39; 'to:addr:python.org': 0.39; 'skip:d 20': 0.39; "i'd": 0.40; 'subject:from': 0.40; 'more': 0.60; 'your': 0.61; 'target': 0.61; 'kind': 0.61; 'john': 0.62; 'comments,': 0.64; 'making': 0.67; 'subject:without': 0.67; 'care': 0.71; 'subject:class': 0.84; 'zen': 0.84; 'contents,': 0.91; 'increases': 0.93; 'inheritance,': 0.93; 'technique': 0.93; 'absolutely': 0.98
X-Injected-Via-Gmane http://gmane.org/
To python-list@python.org
From Peter Otten <__peter__@web.de>
Subject Re: Adding modified methods from another class without subclassing
Date Mon, 22 Aug 2011 11:32:18 +0200
Organization None
References <20110822150445.d351f4761ac00559079f7edc@johnohagan.com>
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Gmane-NNTP-Posting-Host p5084ae33.dip.t-dialin.net
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.304.1314005548.27778.python-list@python.org> (permalink)
Lines 102
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1314005548 news.xs4all.nl 23980 [2001:888:2000:d::a6]:40807
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:12002

Show key headers only | View raw


John O'Hagan wrote:

> 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

That makes me dizzy. Are there any maxims in the Zen of Python that this 
piece doesn't violate?

> 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..

In the standard library functools.total_ordering uses that technique and I 
find the implications hard to understand:

http://bugs.python.org/issue10042

Your decorator looks even more complex; I'd only recommend using it if 
you're absolutely sure you're clever enough to debug it ;)

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Adding modified methods from another class without subclassing Peter Otten <__peter__@web.de> - 2011-08-22 11:32 +0200

csiph-web