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


Groups > comp.lang.python > #11004

Restricted attribute writing

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!news2.arglkargh.de!news.wiretrip.org!newsfeed.xs4all.nl!newsfeed6.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <johnmohagan@gmail.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.001
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'elif': 0.04; 'attributes': 0.05; 'attribute': 0.07; 'bits': 0.07; 'slices': 0.07; 'integers': 0.09; 'modulo': 0.09; 'subclass': 0.09; 'writable': 0.09; 'def': 0.15; 'class,': 0.15; '"""ensure': 0.16; '@property': 0.16; 'attribute,': 0.16; 'int):': 0.16; 'item)': 0.16; 'length)': 0.16; 'simplified': 0.16; 'subject:writing': 0.16; 'simpler': 0.18; 'solutions,': 0.19; 'seems': 0.20; 'index': 0.24; 'sender:addr:gmail.com': 0.25; 'code': 0.25; "i'm": 0.27; 'raise': 0.28; 'lists': 0.28; 'email name:': 0.30; 'class': 0.30; 'changing': 0.31; 'list': 0.32; 'to:addr:python-list': 0.33; 'retain': 0.34; 'lists,': 0.35; 'hold': 0.35; 'charset:us-ascii': 0.36; 'list,': 0.37; 'but': 0.37; 'two': 0.37; 'received:google.com': 0.38; 'received:209.85': 0.38; 'ways': 0.39; 'header:Mime-Version:1': 0.39; 'else': 0.39; 'format.': 0.39; 'to:addr:python.org': 0.39; 'case': 0.39; 'called': 0.40; 'kind': 0.61; 'header:Message-Id:1': 0.61; 'order': 0.62; 'john': 0.62; 'below': 0.62; 'property': 0.63; 'works,': 0.68; 'relevant': 0.69; 'container': 0.73; 'lis': 0.84; 'received:home': 0.91
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=1rB+eFN3K3GWR/KD0d/UxG1Bt1vuzlirtfbTuCfZ1XI=; b=GUpjqkGV0G0pF1xjakwE7x93gqEx16ueXaUIfPsrephvFNlryCGOiKD1z2fYcZK4Xk zYsIXYrEY76apurSr9xaCHmgg5h8BWE7IWdChb2b8fIfkSM3j9uIQPLgmpeDjHI7JyKA ItnKA+vC3dKJWTJ9mwcg7FZlHhIci4WrRcMNk=
Sender "John O'Hagan" <johnmohagan@gmail.com>
Date Mon, 8 Aug 2011 01:35:00 +1000
From John O'Hagan <research@johnohagan.com>
To python-list@python.org
Subject Restricted attribute writing
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 <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.2010.1312731312.1164.python-list@python.org> (permalink)
Lines 74
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1312731312 news.xs4all.nl 23955 [2001:888:2000:d::a6]:55843
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:11004

Show key headers only | View raw


I'm looking for good ways to ensure that attributes are only writable such that they retain the characteristics the class requires. 

My particular case is a class attribute which is initialised as a list of lists of two integers, the first of which is a modulo remainder. I need to be able to write to it like a normal list, but want to ensure it is only possible to do so without changing that format. 

Below is a what I eventually came up with; a container class called OrderElement for the inner lists, and subclass of list called Order for the main attribute, which is a property of the main class, simplified below as SeqSim.  It works, but seems like a hell of a lot of code for a simple idea. I'm interested in ideas for simpler solutions, and general advice on how to do this kind of thing in a straightforward way.  


class OrderElement():
    """Container class which can only hold two integers
       the first of which is a modulo of the 'length' arg"""
    def __init__(self, lis, length):
        self.__data = [None, None]
        self.__length=length
        self[:] = lis    
        
    def __setitem__(self, index, item):
        if isinstance(index, slice):
            inds = range(*index.indices(2))
            for k, v in enumerate(item):
                self[inds[k]] = v
        elif isinstance(item, int):
            if index == 0:
                item %= self.__length
            self.__data[index] = item
        else:
            raise TypeError("OrderElement takes two integers")
            
    def __getitem__(self, index):
        return self.__data[index]


class Order(list):
    """Can only contain OrderElements"""
    def __init__(self, lis, length):
        self.__length = length
        self[:] = lis
        
    def __setitem__(self, index, item):
        if isinstance(index, slice):
            item = [i if isinstance(i, OrderElement)
                else OrderElement(i, self.__length)
                for i in item]
        elif not isinstance(item, OrderElement):
            item = OrderElement(item, self.__length)           
        list.__setitem__(self, index, item)
            
    def __getitem__(self, index):
        """Ensure slices are of the same class"""
        if isinstance(index, slice):
            return self.__class__(list.__getitem__(self, index),
            self.__length)
        return list.__getitem__(self, index)

                        
class SeqSim():
    """Just the relevant bits of the main class"""
    def __init__(self, lis, length):
        self.__order = Order(lis, length)
        self.length = length        

    @property
    def order(self):
        return self.__order
        
    @order.setter
    def order(self, lis):
        if not isinstance(lis, Order):
            lis = Order(lis, self.length)
        self.__order = lis

-- 

John O'Hagan

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


Thread

Restricted attribute writing John O'Hagan <research@johnohagan.com> - 2011-08-08 01:35 +1000
  Re: Restricted attribute writing Roy Smith <roy@panix.com> - 2011-08-07 12:07 -0400
    Re: Restricted attribute writing Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-08 02:31 +1000
      Re: Restricted attribute writing Rafael Durán Castañeda <rafadurancastaneda@gmail.com> - 2011-08-07 18:53 +0200
      Re: Restricted attribute writing Rafael Durán Castañeda <rafadurancastaneda@gmail.com> - 2011-08-07 18:56 +0200
  Re: Restricted attribute writing Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-08 03:07 +1000
    Re: Restricted attribute writing Chris Angelico <rosuav@gmail.com> - 2011-08-07 19:21 +0100
    Re: Restricted attribute writing John O'Hagan <research@johnohagan.com> - 2011-08-08 14:59 +1000

csiph-web