define

Bengt Richter bokr at oz.net
Mon May 12 23:08:58 EDT 2003


On Mon, 12 May 2003 17:44:54 +0100, Turhan Ozen <txo at cs.nott.ac.uk> wrote:

>
>--------------040100070005090409060908
>Content-Type: text/plain; charset=us-ascii; format=flowed
>Content-Transfer-Encoding: 7bit
>
>__getattr__ is getting into infinite loop. I just copied the code. Could 
>you please help me how to avoid this?
Ok, but please don't top-post, and please don't port html.


I messed around with it, and made an incomplete unit test for it too:
(had to include enumerate, since this was 2.2.2 on windows).
The unit test is just a hack, fthoi. I cannibalized an example
from diveintopython (I think), in case you recognize some class names ;-)

====< lwn.py >=======================================================
def enumerate(seq):
    return zip(range(len(seq)), seq)

class list_with_names(list):
    def __init__(self, names):
        assert isinstance(names, (list,tuple)) and map(type, names)==[str]*len(names)
        list.__init__(self, len(names)*[None])
        self.__names = {}
        for i, name in enumerate(names):
            self.__names[name] = i
    def names(self):
        itrev = [(v,k) for k,v in  self.__names.items()]
        itrev.sort()
        return [k for v,k in itrev]
    def __getattribute__(self, name):
        try:
            return self[list.__getattribute__(self, '_list_with_names__names')[name]]
        except KeyError:
            return list.__getattribute__(self, name) 
    def __setattr__(self, name, value):
        if name == '_list_with_names__names':
             list.__setattr__(self, name, value)
             return
        try:
            ixdict = list.__getattribute__(self, '_list_with_names__names')
            self[ixdict[name]] = value
        except KeyError:
            raise AttributeError, 'list_with_names attribute %r undefined' % name
=====================================================================
====< testlwn.py >===================================================
"""Unit test for lwn.py"""
import lwn
import unittest

class KnownValues(unittest.TestCase):
    knownValues = (
        # (unsplit_names, init_value_list)
        ('zero one two', ['ZER0', 111, 222]),
        ('a b c d e', [chr(x) for x in range(ord('A'),ord('E')+1)]),
        ('', []),
    )
    
    def testLwnKnownValues(self):
        """lwn should give known result with known input"""
        for namestr, vals in self.knownValues:
            result = lwn.list_with_names(namestr.split())
            self.assertEqual(`type(result)`, "<class 'lwn.list_with_names'>")
            self.assertEqual([None]*len(namestr.split()), result)
            result[:] = vals
            self.assertEqual(`type(result)`, "<class 'lwn.list_with_names'>") 
            i=0;
            for name in result.names():
                self.assertEqual(result[i], getattr(result, name))
                i += 1

class lwnBadInput(unittest.TestCase):
    def testBadAttr(self):
        """lwn should fail with unknown attr after init"""
        result = lwn.list_with_names('a b'.split())
        self.assertRaises(AttributeError, lambda att: result.att, 'x')
        self.assertEqual(getattr(result, 'a'), None)

    def testNonNamelist(self):
        """lwn should fail with non-namelist input"""
        self.assertRaises(AssertionError, lwn.list_with_names, 12345)
        self.assertRaises(AssertionError, lwn.list_with_names, [7])
        self.assertRaises(AssertionError, lwn.list_with_names, (8))

class SanityCheck(unittest.TestCase):
    def testSanity(self):
        """Initializations should be Nones for each name & names() should be ordered"""
        for n in xrange(10):
            names = [chr(x+65) for x in xrange(n)]
            obj = lwn.list_with_names(names)
            self.assertEqual(obj, [None]*n)
            self.assertEqual(obj.names(), names)

if __name__ == "__main__":
    unittest.main()
=====================================================================

[20:09] C:\pywk\clp>testlwn.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.020s

OK
Regards,
Bengt Richter




More information about the Python-list mailing list