Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions test/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,12 +274,14 @@ def test_invalid_index(self):
self.assertRaisesRegex(TypeError, 'slice indices', lambda: x["0":"1"])

def test_zero_dim_index(self):
# We temporarily support indexing a zero-dim tensor as if it were
# a one-dim tensor to better maintain backwards compatibility.
x = torch.tensor(10)
with warnings.catch_warnings(record=True) as w:
self.assertEqual(x, x[0])
self.assertEqual(len(w), 1)
self.assertEqual(x, x.item())

def runner():
print(x[0])
return x[0]

self.assertRaisesRegex(IndexError, 'invalid index', runner)


# The tests below are from NumPy test_indexing.py with some modifications to
Expand Down
8 changes: 3 additions & 5 deletions torch/csrc/autograd/python_variable_indexing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,9 @@ static Variable applySlice(const Variable& self, int64_t dim, PyObject* slice, b

static Variable applySelect(const Variable& self, int64_t dim, int64_t index) {
if (index == 0 && dim == 0 && self.dim() == 0) {
// Deprecated support for indexing 0-dim tensors as if they were 1-dim.
PyErr_WarnEx(PyExc_UserWarning,
"invalid index of a 0-dim tensor. This will be an error in PyTorch 0.5. "
"Use tensor.item() to convert a 0-dim tensor to a Python number", 1);
return at::alias(self);
throw IndexError(
"invalid index of a 0-dim tensor. "
"Use tensor.item() to convert a 0-dim tensor to a Python number");
}
int64_t size = self.size(dim);
if (index < -size || index >= size) {
Expand Down