Negative form of isinstance() in Python
Asked Answered
T

3

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

Tabernacle answered 31/7, 2012 at 20:41 Comment(4)
So you don't mean not isinstance(...)?Augsburg
so you need to learn how to use not for every python construction?Incudes
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.)Commensurate
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).Mimeograph
L
55

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

Linehan answered 31/7, 2012 at 20:43 Comment(0)
A
33

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
Anacoluthon answered 31/7, 2012 at 20:43 Comment(0)
S
7

Just use not, e.g.,

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

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

Suggestible answered 31/7, 2012 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.