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
13 changes: 13 additions & 0 deletions test/test_torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -11324,6 +11324,19 @@ def test_c10_layer_norm(self):
weight), torch.tensor(bias), 1, epsilon, True)
torch.testing.assert_allclose(expected_norm, actual_norm)

def test_subclass_tensors(self):
# raise an error when trying to subclass FloatTensor
with self.assertRaisesRegex(TypeError, "type 'torch.FloatTensor' is not an acceptable base type"):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious if this error message is actually stable -- I guess the CI will tell us.

class Foo1(torch.FloatTensor):
pass

# but allow subclassing Tensor:
class Foo2(torch.Tensor):
def foo(self):
return 5
f = Foo2()
self.assertEqual(f.foo(), 5)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer doing something with the Tensor, e.g. you could just check it's shape is () here.


# Functions to test negative dimension wrapping
METHOD = 1
INPLACE_METHOD = 2
Expand Down
4 changes: 3 additions & 1 deletion torch/csrc/tensor/python_tensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ static void py_initialize_tensor_type(PyTypeObject& type, const char* name, PyOb
((PyObject*)&type)->ob_refcnt = 1;
((PyObject*)&type)->ob_type = &metaclass;
type.tp_basicsize = sizeof(PyTensorType);
type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
// Subclassing from torch.<ScalarType>Tensor isn't supported.
// (Py_TPFLAGS_BASETYPE omitted). Subclassing torch.Tensor still allowed.
type.tp_flags = Py_TPFLAGS_DEFAULT;
type.tp_name = name;
type.tp_new = Tensor_new;
if (PyType_Ready(&type) < 0) {
Expand Down