Is there any way to deny something like isinstance () in Python?

2

To make my question clearer, I give an example in code R which is the language in which I have a little more experience. Suppose I have the simple variable "a" that is worth 5. First of all I want to validate if it is numeric using is.numeric:

a <- 5
is.numeric(a)
[1] TRUE

Now, to check if it is not numerical, we use a sign! before the method and we get the following:

!is.numeric(a)
[1] FALSE

My question is whether it is possible to do something like that in Python, "denying" a method like isinstance () that follows the structure:

isinstance(variable, tipo)

For example, if we apply negation to isinstance, I get:

a= 5
!isinstance(a, int)

"isinstance" no se reconoce como un comando interno o externo,
programa o archivo por lotes ejecutable.

I did not find any useful information, so I pose my question. If there is material that I have overlooked, I would also greatly appreciate it if you would let me know.

    
asked by Alejandro Carrera 16.11.2018 в 20:50
source

2 answers

4

The negation operator in Python is not .

>>> a= 5
>>> not isinstance(a, int)
False

The admiration ! is not a valid symbol in Python, although you can use it in certain interactive interpreters, such as Jupyter Notebook or IPython. In them it serves to invoke external commands of the operative (shell), which explains the error message that you could see (who does not recognize isinstance as a valid command is the shell ).

    
answered by 16.11.2018 / 20:59
source
3

The way to deny in Python is directly a not for example:

a = 5
print(isinstance(a, int))
print(not isinstance(a, int))

True
False

What you have to keep in mind are some peculiarities of Python with respect to R. is.numeric() of R is a function of higher level than isinstance() of Python, isinstance() verifies an object to see if it matches a certain class, and in base Python, as in R, there are several classes that can be considered numerical (in fact there are more):

In R:

is.numeric(5.0) # TRUE
is.numeric(5L)  # TRUE

In Python

isinstance(5, int)   # TRUE
isinstance(5.0, int) # FALSE

The trick in Python is to pass to isinstance() a list with the classes to verify, obviously with those that we consider numeric. it could be something like this: isinstance(5.0, (int, float)) , however something more comfortable, is to take advantage of the numbers module to know the classes that we should consider numerical:

import numbers

def isnumeric(x):
  return isinstance(x, numbers.Number)

print(isnumeric(5))
print(isnumeric(5.0))

True
True
    
answered by 16.11.2018 в 21:21