[fx] improve args mutation error (#51175)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/51175
gives a suggestion about how to deal with immutable args/kwargs list
Test Plan: Imported from OSS
Reviewed By: jamesr66a
Differential Revision: D26093478
Pulled By: zdevito
fbshipit-source-id: 832631c125561c3b343539e887c047f185060252
diff --git a/test/test_fx.py b/test/test_fx.py
index c0a5af4..f380259 100644
--- a/test/test_fx.py
+++ b/test/test_fx.py
@@ -1438,6 +1438,12 @@
i += 1
self.assertEqual(i, 3)
+ def test_no_mutation(self):
+ from torch.fx.immutable_collections import immutable_list
+ x = immutable_list([3, 4])
+ with self.assertRaisesRegex(NotImplementedError, "new_args"):
+ x[0] = 4
+
def run_getitem_target():
from torch.fx.symbolic_trace import _wrapped_methods_to_patch
diff --git a/torch/fx/immutable_collections.py b/torch/fx/immutable_collections.py
index 03cb329..459c30e 100644
--- a/torch/fx/immutable_collections.py
+++ b/torch/fx/immutable_collections.py
@@ -1,5 +1,13 @@
+
+_help_mutation = """\
+If you are attempting to modify the kwargs or args of a torch.fx.Node object,
+instead create a new copy of it and assign the copy to the node:
+ new_args = ... # copy and mutate args
+ node.args = new_args
+"""
+
def _no_mutation(self, *args, **kwargs):
- raise NotImplementedError(f"'{type(self).__name__}' object does not support mutation")
+ raise NotImplementedError(f"'{type(self).__name__}' object does not support mutation. {_help_mutation}")
def _create_immutable_container(base, mutable_functions):
container = type('immutable_' + base.__name__, (base,), {})