Search code examples
pythonreal-number

checking if python object can be interpreted as real number [python]


I wrote the function in python:

def is_number_like(x):
     try:
        int(x) + 1
    except:
        return False
    return True

is there any difference if I write float(x) or int(x)? Or could + 1 part be useful in some case?

EDIT: is_number_like will return True when string is passed - that is what I don't want to be. I would like a function which will return False anytime a text-like value is passed as an argument. Is there a method for this?

maybe:

def is_number_like(x):
     try:
        x + 1
    except:
        return False
    return True

will be better?

or maybe:

def is_number_like(x):
     try:
        float(x + 1) == float(x) + 1
    except:
        return False
    return True

I want to write a module which would accept any well-behaved number type which represents one dimensional real number (for example SimpleITK.sitkUInt8 number type or numpy.int32 and so on...).

I'm afraid that there could be libraries, which will not throw an error in casting to int or float. For example I can imagine situation like this:

>>> z = SomeComplexType(1. + 2.j)
>>> z
(1+2j)
>>> z -= 2.j
>>> z
(1+0j)
>>> float(z) # does not raise an error
1.

is this possible, should I worry about such situation?

And do all well designed real number types will cast to float without an error?

ps. i have read this already: How do I check if a string is a number (float)?


Solution

  • If I understand correctly, what you're actually trying to do is find out whether an object behaves in "number"-like ways (e.g. can you append +1 to it). If so, there's an easier way:

    >>> from numbers import Number
    >>> 
    >>> my_complex_number = 3-2j
    >>> my_stringy_number = "3.14"
    >>>
    >>> isinstance(my_complex_number, Number)
    True
    >>> isinstance(my_stringy_number, Number)
    False