Style guide for subclassing built-in types?

janeaustine50 at hotmail.com janeaustine50 at hotmail.com
Wed Feb 23 20:35:24 EST 2005


Michael Spencer wrote:
> janeaustine50 at hotmail.com wrote:
> > Kent Johnson wrote:
> >
> >>janeaustine50 at hotmail.com wrote:
> >>
> >>>p.s. the reason I'm not sticking to reversed or even reverse :
> >
> > suppose
> >
> >>>the size of the list is huge.
> >>
> >>reversed() returns an iterator so list size shouldn't be an issue.
> >>
> >>What problem are you actually trying to solve?
> >>
> >>Kent
> >>
> >
> >
> > Oh, you are right.
> >
> > Actually, it's more complicated than simple reversion. The list
order
> > should be somewhat "twisted" and the list is big.
> >
> > For example,
> >
> > [1,2,3,4,5,6,7,8,9,10]
> >
> > --> [10,9,8,7,6,1,2,3,4,5]
> >
> > so __getitem__(self,i) => __getitem__(self,-i-1) if i<len(size)/2,
> > otherwise __getitem__(self,i-len(size)/2)
> >
> > I'd like to have TwistedList class that takes in an original list
and
> > pretends as if it is twisted actually. However, I have to have
> > duplicate codes here and there to make it act like a "list", say
assert
> > twisted_list == [10,9,...] and for each in twisted_list and etc.
> >
> If you want a twisted 'view' of an existing list, then a wrapper
makes most sense.
>
> If, however, you only need the twisted version, why not simply
override
> list.__init__ (and extend, append etc... as required):
>
>   >>> class rev_list(list):
>   ... 	def __init__(self, iterable):
>   ... 		list.__init__(self, iterable[::-1])
>   ...
>   >>> l = rev_list([1,2,3])
>   >>> l
>   [3, 2, 1]
>
> Michael

Thank you but your advice doesn't fit in my case since I want to keep
the memory usage and the initial time minimum. iterable[::-1] would
build another list and it would take big memory and time during
reversing if iterable were huge. (and the "iterable" wouldn't be
garbage-collected because I want to keep a reference to it)




More information about the Python-list mailing list