PyCQA / flake8-bugbear

A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.
MIT License
1.05k stars 103 forks source link

How to handle B015 within pytest.raises blocks #462

Open jvavrek opened 4 months ago

jvavrek commented 4 months ago

Often when defining custom objects we end up testing that the __eq__ raises a particular error for unsupported comparisons. In practice, this means we have an unused comparison that triggers the B015 rule—see the MWE below. I wonder if there's a recommended way to get around this (without suppressing B015 altogether), or whether it could say be disabled within a with pytest.raises context.

Minimal working example:

# B015.py
import pytest

class MyClass:
    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        if not isinstance(other, MyClass):
            raise TypeError(f"Cannot compare with {type(other)}")
        return self.x == other.x

a = MyClass(5)
b = MyClass(5)
c = MyClass(4)

assert a == b
assert a != c
with pytest.raises(TypeError):
    a == a.x
$ flake8 B015.py 
B015.py:21:5: B015 Result of comparison is not used. This line doesn't do anything. Did you intend to prepend it with assert?