diff --git a/docs/violations/README.md b/docs/violations/README.md index 5d2ebd4..54304c1 100644 --- a/docs/violations/README.md +++ b/docs/violations/README.md @@ -7,6 +7,7 @@ | ----------------- | ---------------------------------------------------------- | | [TC002](TC002.md) | Create your own exception | | [TC003](TC003.md) | Avoid specifying long messages outside the exception class | +| [TC004](TC004.md) | Prefer `TypeError` exception for invalid type | ## `TC1xx` - General diff --git a/docs/violations/TC004.md b/docs/violations/TC004.md new file mode 100644 index 0000000..fe9d26c --- /dev/null +++ b/docs/violations/TC004.md @@ -0,0 +1,31 @@ +# `TC004` - Prefer `TypeError` exception for invalid type + +## Why is it bad + +Using semantically incorrect exceptions results in confusing diagnostic information for the user. + +The Python docs make the definition clear: + +> Raised when an operation or function is applied to an object of inappropriate type. [...] +This exception may be raised by user code to indicate that an attempted operation on an object is not supported [...] +Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError. + +[Source](https://docs.python.org/3/library/exceptions.html#TypeError) + +## How it looks like + +```py +if isinstance(my_var, int): + pass +else: + raise ValueError(f'{my_var} must be an int') +``` + +## How it should be + +```py +if isinstance(my_var, int): + pass +else: + raise TypeError(f'{my_var} must be an int') +```