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


Groups > comp.lang.python > #11024

Re: Restricted attribute writing

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!newsfeed.xs4all.nl!newsfeed6.news.xs4all.nl!xs4all!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; 'override': 0.07; 'rest,': 0.07; 'slices': 0.07; 'python': 0.08; 'modulo': 0.09; 'subclasses': 0.09; 'supported,': 0.09; 'writable': 0.09; 'def': 0.15; '(0,': 0.16; '[2,': 0.16; 'accordingly,': 0.16; 'appends': 0.16; 'behaviour,': 0.16; 'containers': 0.16; 'dot-notation': 0.16; 'int)': 0.16; 'integers.': 0.16; 'length,': 0.16; 'overrides': 0.16; 'realised': 0.16; 'redone': 0.16; 'slicing': 0.16; 'subject:writing': 0.16; 'mon,': 0.16; 'wrote:': 0.16; 'meant': 0.17; 'int': 0.18; 'insert': 0.19; 'holds': 0.21; 'header :In-Reply-To:1': 0.22; 'obviously': 0.23; 'helper': 0.23; 'incorrect': 0.23; 'changed': 0.24; 'aug': 0.24; 'index': 0.24; 'sender:addr:gmail.com': 0.25; "i'm": 0.27; 'raise': 0.28; 'random': 0.28; "wasn't": 0.28; 'lists': 0.28; 'import': 0.28; 'operations': 0.30; 'for,': 0.30; 'protects': 0.30; 'thanks': 0.30; 'class': 0.30; 'changes': 0.31; 'changing': 0.31; 'shows': 0.32; 'list': 0.32; 'usually': 0.32; "isn't": 0.33; 'it.': 0.33; "can't": 0.33; 'to:addr:python-list': 0.33; 'it?': 0.33; "i've": 0.34; 'be.': 0.34; 'idea': 0.34; 'retain': 0.34; 'starting': 0.36; 'charset:us-ascii': 0.36; 'properties': 0.36; 'problems': 0.36; 'class.': 0.37; 'skip:z 20': 0.37; 'things,': 0.37; 'using': 0.37; 'list,': 0.37; 'but': 0.37; 'something': 0.37; 'two': 0.37; 'think': 0.38; 'steven': 0.38; 'received:google.com': 0.38; 'should': 0.38; 'subject:: ': 0.39; 'aside': 0.39; 'etc.)': 0.39; 'itself.': 0.39; 'ways': 0.39; 'enough': 0.39; 'header:Mime- Version:1': 0.39; 'format.': 0.39; 'why': 0.39; 'to:addr:python.org': 0.39; 'case': 0.39; 'received:74.125': 0.39; "i'd": 0.40; 'third': 0.40; 'happens': 0.40; 'your': 0.61; 'header :Message-Id:1': 0.61; 'order': 0.62; 'john': 0.62; 'property': 0.63; 'full': 0.63; 'making': 0.67; 'validate': 0.67; 'special': 0.67; 'unnecessary': 0.73; '100': 0.73; '(easily)': 0.84; '(int,': 0.84; '12)': 0.84; '[[1,': 0.84; 'value):': 0.84; 'items,': 0.91; '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:in-reply-to:references :x-mailer:mime-version:content-type:content-transfer-encoding; bh=4OG6rqf9fIZde6+mXJCvNmUqAwdCcDJlEZfV9W5pOVc=; b=dhVrTB5TTIFjjkfUm0aVSioJAU3nlUzY4Kl48PRa5NsKy1tbThx8Fn/bvtANR5Iyo5 d6CTkCAyVtuxwKJg5wcoEEiwurgrTj0aT+VahnOLk48pLrBsYfw6ucJffrdqzyRLf2cr /dz4V1ghqn9wnw2/X2dJzyPgFnBi05HGsbSXc=
Sender "John O'Hagan" <johnmohagan@gmail.com>
Date Mon, 8 Aug 2011 14:59:23 +1000
From John O'Hagan <research@johnohagan.com>
To python-list@python.org
Subject Re: Restricted attribute writing
In-Reply-To <4e3ec653$0$29987$c3e8da3$5496439d@news.astraweb.com>
References <mailman.2010.1312731312.1164.python-list@python.org> <4e3ec653$0$29987$c3e8da3$5496439d@news.astraweb.com>
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.2023.1312779580.1164.python-list@python.org> (permalink)
Lines 117
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1312779580 news.xs4all.nl 23853 [2001:888:2000:d::a6]:52766
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:11024

Show key headers only | View raw


On Mon, 08 Aug 2011 03:07:30 +1000
Steven D'Aprano <steve+comp.lang.python@pearwood.info> wrote:

> John O'Hagan wrote:
> 
> > I'm looking for good ways to ensure that attributes are only writable such
> > that they retain the characteristics the class requires.
> 
> That's what properties are for.
> 
> > 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.
> 
> Then you have two problems to solve.
> 
> First, you need a special type of list that only holds exactly two integers.
> Your main class can't control what happens inside the list, so you need the
> list to validate itself.
> 
> Secondly, you should use a property in your main class to ensure that the
> attribute you want to be a special list-of-two-ints can't (easily) be
> changed to something else.
>

Although experience shows you're usually right :) , I thought I had three problems, the third being what I perhaps wasn't clear enough about: that the two-integer containers live in a list which should only contain the two-integer things, but aside from that should be able to do all the other list operations on it. AFAIK making this attribute a property only protects it from incorrect assignment, but not from unwanted appends etc.  

That's what the other helper class Order is meant for, it subclasses list, and overrides __setitem__ to ensure every item is an OrderElement, and __getitem__ to ensure slices are the same class. I've also since realised it must override append, insert and extend. I think I need all this to ensure the required behaviour, including:

s = SeqSim([[15, 2]], 12)
s.order[0][1] = 100
s.order[0][1:] = [100]
s.order += [[22, 11]]
s.order *= 2
s.order[2] = [[15, 8]]
s.order[1:5:2]) = [[1, 1],[2, 2]]
s.order.extend([[1, 1],[2, 2]])
s.order.insert(2, [2, 29])
s.order.append([26, 24])
s.order.extend(s.order[1:3])
s.order = [[99, 99],[100, 100]]
import random
random.shuffle(s.order)
etc
[...]
> I'd take this approach instead:
> 
> # Untested.
> class ThingWithTwoIntegers(object):
>     def __init__(self, a, b):
>         self.a = a
>         self.b = b
>     def __getitem__(self, index):
>         # Slicing not supported, because I'm lazy.
>         if index < 0: index += 2
>         if index == 0: return self.a
>         elif index == 1: return self.b
>         else: raise IndexError
>     def __setitem__(self, index, value):
>         # Slicing not supported, because I'm lazy.
>         if index < 0: index += 2
>         if index == 0: self.a = value
>         elif index == 1: self.b = value
>         else: raise IndexError
>     def _geta(self):
>         return self._a
>     def _seta(self, value):
>         if isinstance(value, (int, long)):  # drop long if using Python 3
>             self._a = value
>         else:
>             raise TypeError('expected an int but got %s' % type(value))
>     a = property(_geta, _seta)
>     # and the same for b: _getb, _setb, making the obvious changes
> 
[...]
> Obviously this isn't a full blown list, but if you don't need all the
> list-like behaviour (sorting, inserting, deleting items, etc.) why support
> it?
> 

Thanks for this, I can see that the __data attribute I was using was unnecessary and I've redone the OrderElement class accordingly, although I do want slicing and don't need dot-notation access:

class OrderElement():

    def __init__(self, length, a, b):
        self.__length=length
        self.__a = a
        self.__b = b
        self[:] = a, b
        
    def __setitem__(self, index, item):
        if isinstance(index, slice):
            for k, i in zip(range(*index.indices(2)), item):
                self[k] = i
        elif isinstance(item, int) and index in (0, 1):
            if index == 0:
                self.__a = item % self.__length
            elif index == 1:
                self.__b = item
        else:
            raise TypeError("OrderElement takes two integers")
            
    def __getitem__(self, index):
        if isinstance(index, slice):
           return [self[i] for i in range(*index.indices(2))]
        if index == 0:
            return self.__a
        if index == 1:
            return self.__b
        raise IndexError

As for the rest, I take your point that a simple idea need not be simple to implement, and I'm starting to think my solution may be about as complicated as it needs to be. 

Regards,

John

Back to comp.lang.python | Previous | NextPrevious 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