Add a better error message when unsupported ops are used for Dimension

This fix is related to 25790. In 25790, `Dimension` with division will
thrown an TypeError:
```
output_dim = input_shape[-1] / 2
...
TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'
```
The error is expected, as Dimension only support `//` (not `/`).

However, for backward compatible reasons, `__div__`(`/`) is actually
implemented (but deprecated). See code.

This issue causes confusion and it has been mentioned multiple times
in GitHub and StackOverflow(https://stackoverflow.com/questions/51692253/typeerror-unsupported-operand-types-for-dimension-and-int)

This fix is an attempt to print a better error message with:
```
TypeError: unsupported operand type(s) for /: 'Dimension' and 'int', please use // instead
```

Note that this PR does not change any current behavior, and have no impact with respect
to backward-compatible `__div__`. It merely adds additional notes in the error message.

Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
This commit is contained in:
Yong Tang 2019-02-18 00:25:24 +00:00
parent 130aebaa1e
commit 7e5d6c25f4

View File

@ -468,6 +468,54 @@ class Dimension(object):
""" """
return self // other return self // other
def __rdiv__(self, other):
"""Use `__floordiv__` via `x // y` instead.
This function exists only to have a better error message. Instead of:
`TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`,
this function will explicitly call for usage of `//` instead.
Args:
other: Another `Dimension`.
Raises:
TypeError.
"""
raise TypeError("unsupported operand type(s) for /: '{}' and 'Dimension', "
"please use // instead".format(type(other).__name__))
def __truediv__(self, other):
"""Use `__floordiv__` via `x // y` instead.
This function exists only to have a better error message. Instead of:
`TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'`,
this function will explicitly call for usage of `//` instead.
Args:
other: Another `Dimension`.
Raises:
TypeError.
"""
raise TypeError("unsupported operand type(s) for /: 'Dimension' and '{}', "
"please use // instead".format(type(other).__name__))
def __rtruediv__(self, other):
"""Use `__floordiv__` via `x // y` instead.
This function exists only to have a better error message. Instead of:
`TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`,
this function will explicitly call for usage of `//` instead.
Args:
other: Another `Dimension`.
Raises:
TypeError.
"""
raise TypeError("unsupported operand type(s) for /: '{}' and 'Dimension', "
"please use // instead".format(type(other).__name__))
def __mod__(self, other): def __mod__(self, other):
"""Returns `self` modulo `other`. """Returns `self` modulo `other`.