pytorch/torch/fx/immutable_collections.py
Zachary DeVito fc1d6bf135 [fx] make sure args/kwargs are immutable (#46325)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/46325

Otherwise, mutating them would make the uses/users lists inaccurate.
You can still mutate the node by assigning a new value to .args or .kwargs

Test Plan: Imported from OSS

Reviewed By: jamesr66a

Differential Revision: D24308672

Pulled By: zdevito

fbshipit-source-id: a5305e1d82668b36e46876c3bc517f6f1d03dd78
2020-10-14 15:51:43 -07:00

17 lines
895 B
Python

def _no_mutation(self, *args, **kwargs):
raise NotImplementedError(f"'{type(self).__name__}' object does not support mutation")
def _create_immutable_container(base, mutable_functions):
container = type('immutable_' + base.__name__, (base,), {})
for attr in mutable_functions:
setattr(container, attr, _no_mutation)
return container
immutable_list = _create_immutable_container(list,
['__delitem__', '__iadd__', '__imul__', '__setitem__', 'append',
'clear', 'extend', 'insert', 'pop', 'remove'])
immutable_list.__reduce__ = lambda self: (immutable_list, (tuple(iter(self)),))
immutable_dict = _create_immutable_container(dict, ['__delitem__', '__setitem__', 'clear', 'pop', 'popitem', 'update'])
immutable_dict.__reduce__ = lambda self: (immutable_dict, (iter(self.items()),))