Skip to content
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

Use class setter properties if present #4682

Merged
merged 5 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
31 changes: 31 additions & 0 deletions test/data/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,34 @@ def test_data_share_memory():
for data in data_list:
assert data.x.is_shared()
assert torch.allclose(data.x, torch.full((8, ), 4.))


def test_data_subclass_setter():
class Graph(Data):
def __init__(self):
super().__init__()
self.my_attr = 1.0
self.my_attr2 = 2

@property
def my_attr(self):
return self._my_attr

@my_attr.setter
def my_attr(self, value):
self._my_attr = int(value)

g = Graph()
assert g._store == {'my_attr2': 2}
assert '_my_attr' in g._store.__dict__
assert isinstance(g.my_attr, int)

x = torch.tensor([[1, 2], [3, 4]])
g.x = x
assert g._store == {'x': x, 'my_attr2': 2}

g.my_attr = 2.0
assert isinstance(g.my_attr, int)

g.my_attr2 = 'asdf'
assert g._store == {'x': x, 'my_attr2': 'asdf'}
6 changes: 5 additions & 1 deletion torch_geometric/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,11 @@ def __getattr__(self, key: str) -> Any:
return getattr(self._store, key)

def __setattr__(self, key: str, value: Any):
setattr(self._store, key, value)
propobj = getattr(self.__class__, key, None)
if propobj is None or propobj.fset is None:
setattr(self._store, key, value)
else:
propobj.fset(self, value)

def __delattr__(self, key: str):
delattr(self._store, key)
Expand Down