Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative form of isinstance() in Python

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

like image 658
mrl Avatar asked Jul 31 '12 20:07

mrl


People also ask

What is the opposite of Isinstance in Python?

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

What does Isinstance () do in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

What is the difference between the type () and Isinstance () in Python?

type() returns the type of the object you put in as an argument, and is usually not useful unless compared with a real type (such as type(9) == int ). isinstance() returns a boolean - true or false - based on whether the object is of given type.

What is a negation in Python?

Negation: The not operator in Python can be used only in the unary form, which means negation, returning the a result that is the opposite of its operand. Its boolean prototype is not (bool) -> bool.


2 Answers

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

like image 94
Silas Ray Avatar answered Sep 28 '22 03:09

Silas Ray


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 
like image 25
Igor Chubin Avatar answered Sep 28 '22 04:09

Igor Chubin