New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Slice indexes passed to __getitem__ are wrapped #40411
Comments
Hi, When a slice is passed to __getitem__, the indices for class C:
def __getitem__(self, item): print item
def __len__(self): return 10 >>> x = C()
>>> x[-3]
-3
>>> x[-3:-2]
slice(7, 8, None) This seems to be incorrect (at least inconsistent). However, it truly becomes a BUG when one tries to class C: # Emulated list type
def __init__(self, d):
self.data = d
def __len__(self):
return len(self.data)
def __getitem__(self, item):
if isinstance(item, slice):
indices = item.indices(len(self))
return [self[i] for i in range(*indices)]
else:
return self.data[item]
x = [1, 2, 3]
y = C([1, 2, 3]) >>> x[-7:-5]
[]
>>> print y[-7:-5]
[1] (incorrect behavior) Here the item.indices method does the exact same I would advise that you make the slices object passed Thanks, |
Logged In: YES You'll be happier if you make your classes new-style. I don't know if it's worth changing old-style classes at |
Logged In: YES I'm not sure what you mean by 'make your classes new-style'. According to If you subclass the built-in list type, then the __getitem__ So I can't see any reasonable way to get around this bug. You can try and modify the class C shown above, so that it y = C([1, 2, 3])
>>> print y[-7:-5] # should be []. |
Logged In: YES 'make your classes new-style' == subclass object. >>> class C(object):
... def __getitem__(self, item): print item
... def __len__(self): return 10
...
>>> C()[-3:-2]
slice(-3, -2, None) |
This looks like a duplicate of bpo-723806 which was closed as "won't |
Will close this one as a duplicate of bpo-723806 unless someone springs to |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: