Negative form of isinstance() in Python

Question:

How would I use a negative form of Python’s isinstance()?

Normally negation would work something like

x != 1

if x not in y

if not a

I just haven’t seen an example with isinstance(), so I’d like to know if there’s a correct way to used negation with isinstance().

Asked By: mrl

||

Answers:

That would seem strange, but:

if not isinstance(...):
   ...

The isinstance function returns a boolean value. That means that you can negate it (or make any other logical operations like or or and).

Example:

>>> a="str"
>>> isinstance(a, str)
True
>>> not isinstance(a, str)
False
Answered By: Igor Chubin

Just use not. isinstance just returns a bool, which you can not like any other.

Answered By: Silas Ray

Just use not, e.g.,

if not isinstance(someVariable, str):
     ....

You are simply negating the “truth value” (ie Boolean) that isinstance is returning.

Answered By: Levon
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.