python - What happens in `list.__getslice__` and `list__setslice__` when slicing? -
i'm trying subclass list
builtin, new list acting strangely , believe __setslice__
& __getslice__
blame. changes make list
aren't invasive , behind-the-scenes; user, should behave regular list
.
the problem comes when user wants clear list. executed following test (at repl.it) , got strange result:
class ihatecoding(list): def __getslice__(self, *args): print 'get', args return super(ihatecoding, self).__getslice__(*args) def __setslice__(self, *args): print 'set', args super(ihatecoding, self).__setslice__(*args) >>> l = ihatecoding() >>> l.extend(xrange(5)) >>> l[:] = [] set (0, 2147483647, [])
where 2147483647
value come from, , why return view?
edit:
there's 1 more strange output i've discovered. can explain this?
>>> l[:-1] (0, 2) #expected `-1`
that value of sys.maxint
, "largest possible integer":
>>> sys.maxint 2147483647
since sliced without specifying start , end, start 0 , end "infinity", or biggest integer python can use. documented here.
the term somelist[:]
slicing, somelist[2:4]
, etc. it's slice without start or end specified. i'm not sure quite mean "view". slice of any length list returns copy of portion of list. if slice without start or end, copy of entire list, it's still slicing operation.
note, though, somelist[:]
expression different somelist[:]
target of assignment, you're doing. doing somelist[:]
returns copy, assigning slice somelist[:] = blah
modifies list in-place. again, though somelist[:] = blah
slice assignment, same somelist[2:5]
slice assignment. assigning slice of list changes contents of slice; if slice whole list, replaces entire list.
note each type gets define slicing operations differently, way slicing , slice assignment works on numpy arrays not same how works on lists. lists have no real equivalent of numpy "view", reference part of original array, such modifications view modify original array.
Comments
Post a Comment