Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare the type of two variables without generating PyLint warnings?

Tags:

python

Say I have two variables:

a = 123
b = 234

I want to compare their type. Clearly the obvious way is:

type(a) == type(b)

However, pylint gives me a warning, which I would like to avoid if possible:

Using type() instead of isinstance() for a typecheck. (unidiomatic-typecheck)

(I believe this isn't specifically warning about my use.)

In the case of comparing two variable types, isinstance can't be used, I believe.

How do I compare the type of two variables without generating PyLint warnings?

like image 590
Paul Avatar asked Oct 15 '25 04:10

Paul


2 Answers

Just turn off the pylint warning.

On a single line, you can do that thusly:

types_match = type(a) is type(b) # pylint: disable=unidiomatic-typecheck

See https://pylint.readthedocs.io/en/latest/user_guide/message-control.html

like image 110
Matthias Urlichs Avatar answered Oct 20 '25 17:10

Matthias Urlichs


People get too hung up about linters. It's like the PEP 8 style guide. They are guidelines, and you have to use your own judgment.

If you need to know whether the type of something is the same as the type of something else, then absolutely the straightforward

type(a) == type(b)

is the most Pythonic way. It's not idiomatic Python to jump through crazy hoops to do simple things if you can avoid it.

All that said, it is usually not the case in Python that you really need to know whether the types of two things are exactly the same. (See comments by BrenBarn and Chad S.) So the linter may be pointing to a larger "code smell" than just that one line which compares the two types.

like image 40
John Y Avatar answered Oct 20 '25 17:10

John Y