Why does list.__getitem__ return a list instance for subclasses ofthe list type?

Discussion in 'Python' started by dackz, Feb 6, 2007.

  1. dackz

    dackz Guest

    >>> class ListyThing(list): pass
    ....
    >>> assert isinstance(ListyThing()[:], ListyThing) # I expect True!

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AssertionError
    >>> type(ListyThing()[:]) # I expect ListyThing!

    <type 'list'>

    I don't find this intuitive. Is this intentional? I believe this could
    be avoided if list.__getitem__ used "self.__class__()" to make a new
    instance, instead of "list()", but I don't know how that works under
    the hood in C.

    I believe this happens a lot of other cases too. Actually, I wrote up
    some test cases at http://brodierao.com/etc/listslice/ but I haven't
    taken a look at it in quite a while. I believe there's some other
    funky stuff going on there as well.

    Also, this happens with dict too:

    >>> class DictyThing(dict): pass

    ....
    >>> assert isinstance(DictyThing().copy(), DictyThing) # I expect True!

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AssertionError
    >>> type(DictyThing().copy()) # I expect DictyThing!

    <type 'dict'>

    Any thoughts?
     
    dackz, Feb 6, 2007
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kenneth McDonald
    Replies:
    2
    Views:
    393
    Russell Blau
    Jun 16, 2004
  2. Mr. SweatyFinger

    why why why why why

    Mr. SweatyFinger, Nov 28, 2006, in forum: ASP .Net
    Replies:
    4
    Views:
    1,384
    Mark Rae
    Dec 21, 2006
  3. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,853
    Smokey Grindel
    Dec 2, 2006
  4. Greenhorn
    Replies:
    15
    Views:
    1,150
    Keith Thompson
    Mar 6, 2005
  5. syang8
    Replies:
    1
    Views:
    371
    benben
    Nov 1, 2006
  6. Konstantinos Pachopoulos

    cannot __getitem__ from DB reply list

    Konstantinos Pachopoulos, Sep 20, 2007, in forum: Python
    Replies:
    0
    Views:
    387
    Konstantinos Pachopoulos
    Sep 20, 2007
  7. andrew cooke
    Replies:
    1
    Views:
    290
    Steven D'Aprano
    Apr 3, 2011
  8. Greg Hauptmann
    Replies:
    9
    Views:
    507
    Loren Segal
    Jun 16, 2008
Loading...