Search code examples
pythonpep8

"E721: do not compare types, use isinstance()" error


The python PEP 8 linter doesn't like this:

assert type(a) == type(b)

It tells me to use "isinstance()" instead. But to use isinstance I would have to do something like

assert isinstance(a, type(b)) and isinstance(b, type(a))

which seems much more unwiedly, and I don't really see the point.

Is the linter being wise in some way that I can't see? Or am I being wise in some way the linter can't see?


Solution

  • From context added in the comments:

    according to my program's logic, one should have type(a) == type(b) at this point in the code, and I just want to assert that to see that everything is running smoothly

    In this context, you should just ignore the linter because it's not suggesting anything useful to you. E721 was intended to warn people about issues via type-checks such as:

    if type(a) == A:
        ...
    

    The example above may be accidentally bugging the logical flow, by neglecting to consider the possibility that a is an instance of a subclass of A.