46

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().

mrl
  • 1,467
  • 2
  • 14
  • 22
  • 8
    So you don't mean `not isinstance(...)`? – jmetz Jul 31 '12 at 20:43
  • 3
    so you need to learn how to use `not` for every python construction? – JBernardo Jul 31 '12 at 20:44
  • 3
    This is still the Summer of Love, everyone. To be fair, that `not in` works shows that you don't need to have the `not` before the expression but sometimes it can float around a bit, and it's possible that there could have been a preferred Pythonic way other than `not isinstance()`. For example, there could have been some subtle corner case which meant you should use a different form (rather like `type(obj) is list` works sometimes but is suboptimal.) – DSM Jul 31 '12 at 20:53
  • There are two special forms: `x is not y` means the same as `not(x is y)`, and `x not in y` means the same as `not(x in y)`. – MRAB Jul 31 '12 at 22:13

3 Answers3

53

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

Silas Ray
  • 25,682
  • 5
  • 48
  • 63
29

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
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
7

Just use not, e.g.,

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

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

Levon
  • 138,105
  • 33
  • 200
  • 191