Skip to content

Commit

Permalink
docs: add TypeError violation
Browse files Browse the repository at this point in the history
  • Loading branch information
swellander authored and guilatrova committed Nov 22, 2021
1 parent 36f1292 commit d424e7c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/violations/README.md
Expand Up @@ -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

Expand Down
31 changes: 31 additions & 0 deletions 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')
```

0 comments on commit d424e7c

Please sign in to comment.