32

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,028
  • 2
  • 10
  • 20
  • 8
    So you don't mean `not isinstance(...)`? – jmetz Jul 31 '12 at 20:43
  • 2
    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

35

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

Silas Ray
  • 24,298
  • 5
  • 44
  • 60
18

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
  • 51,940
  • 8
  • 108
  • 128
6

Just use not, e.g.,

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

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

Levon
  • 118,296
  • 31
  • 184
  • 178