Python

Python

Made by DeepSource

Explicit exception raised in the assert message PTC-W0032

Bug risk
Major
Autofix

Raising a built-in or a custom exception when assert fails is ineffective. Asserts always raise an AssertionError, making the provided exception which the user is expecting useless. This may lead to runtime errors if this detail is not understood during the exception handling. It is therefore recommended to use if to check the condition and raise the expression explicitly if something is not right.

Bad practice

assert isinstance(num_channels, int), ValueError("Field is not an integer")

Running this will give AssertionError: Field is not an integer and not the expected ValueError.

A better way is to check the condition using an If statement and raise the exception if condition is not satisfied. Like this:

Recommended

if not isinstance(nem_channels, int):
    raise ValueError("Field is not an integer")

This gives the expected output ValueError: Field is not an integer when the condition fails.

Note: If this issue is autofixed, DeepSource will change assert statements to if checks to raise the exception mentioned in the assert fail message.