Skip to content

Commit 960133e

Browse files
authored
Don't fail Variable.__repr__ if the value cannot be retrieved. (#21788)
Under some conditions, converting the variable value to numpy may fail. We don't want to fail `__repr__` in this case. I my example, this was preventing this exception from being raised and osbcuring the real issue: https://github.com/keras-team/keras/blob/master/keras/src/backend/common/variables.py#L281-L288 Additionally, the exception was not reporting the shape used for comparison (`self.shape`).
1 parent adbfd13 commit 960133e

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

keras/src/backend/common/variables.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def assign(self, value):
282282
"The shape of the target variable and "
283283
"the shape of the target value in "
284284
"`variable.assign(value)` must match. "
285-
f"variable.shape={self.value.shape}, "
285+
f"variable.shape={self.shape}, "
286286
f"Received: value.shape={value.shape}. "
287287
f"Target variable: {self}"
288288
)
@@ -399,7 +399,11 @@ def constraint(self, value):
399399
def __repr__(self):
400400
value = None
401401
if hasattr(self, "_value") and self._value is not None:
402-
value = backend.core.convert_to_numpy(self._value)
402+
try:
403+
value = backend.core.convert_to_numpy(self._value)
404+
except:
405+
# In some cases the conversion to numpy can fail.
406+
pass
403407
value_str = f", value={value}" if value is not None else ""
404408
return (
405409
f"<Variable path={self.path}, shape={self.shape}, "

0 commit comments

Comments
 (0)