changing the List's behaviour?

Heather Coppersmith me at privacy.net
Mon Jul 28 10:13:26 EDT 2003


On Mon, 28 Jul 2003 14:46:14 +0200,
Peter Otten <__peter__ at web.de> wrote:

> meinrad recheis wrote:
>> i want to change the List so that it returns None if the index for
>> accesssing list elements
>> is out of bound.

> If you really need it, you can write a class similar to the one below:

> class DefaultList(list):
>     def __init__(self, sequence=[], default=None):

That's asking for trouble.  That mutable default argument for
sequence is evaluated at class definition-time, and all instances
of DefaultList created without a sequence argument will end up
sharing one list.

Do this instead:

class DefaultList( list ):
    def __init__( self, sequence = None, default = None ):
        if sequence is None:
            sequence = [ ]

>         list.__init__(self, sequence)
>         self.default = default
>     def __getitem__(self, index):
>         try:
>             return list.__getitem__(self, index)
>         except IndexError:
>             return self.default

> if __name__ == "__main__":
>     theList = DefaultList("abc", "?")
>     print theList[1]
>     print theList[99]

>     theList = DefaultList(default="X")
>     print theList[1]

Regards,
Heather

-- 
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli





More information about the Python-list mailing list