2

I want to ask if there is a method to check if a value is any number? Is there maybe a "master class" for numbers. I do not want to check every case (int, float, complex). If there is not it is no problem.

In my specific code I now just check every case and than also if it is NaN but that is really annoying.

I have a similar question to data structures: Is there a method that returns whether a value is any of list, tuple, dict or set? Right now I am also checking them every time. So basically my code looks like this:

try:
  value
    if value==None:         #none
      raise Exception("Your value is none")
    elif isinstance(value,str):
      if not value.isnumeric():   #real String
         return value
      else:               #number String
        return (float(value))
    elif isinstance(value,float):
       if math.isnan(value): #nan
         raise Exception("Your number is NaN")
       elif abs(value)>abs(int(value)): #real float
         pass #to-do deal with "real" floats 
       else: #integer
         return int(value)
    elif isinstance(value,int):     #int
      if math.isnan(value): #nan
        raise Exception("Your number is NaN")
      else:
        return value
    elif isinstance(value,tuple):
      pass #to-do recursion
    elif isinstance(value,list):
      pass #to-do recursion
    elif isinstance(value,dict):
      pass #to-do recursion
    elif isinstance(value,set):
      return ("This tool does not support sets yet")
    except NameError: #undefined
        raise Exception("Your value is undefined")

But I feel like it could be much better if there was a method isnumeric() for all values not just strings, like in php.

Regarding my research, I could only find the String isnumeric() method or obviously the type() and isinstance() method.

Please help me but do not tell me there is no better solution.

2
  • 1
    You could try casting to -- for example -- int and see if that fails Commented Jan 22, 2021 at 22:03
  • why avoid built-in functions isinstance() and type()? Commented Jan 22, 2021 at 22:12

3 Answers 3

7

If you're willing to do add an import, this works:

import numbers

variable = 5
print(isinstance(variable, numbers.Number))

For the second question, do

x = {}
print(type(x) in [list, dict, tuple, set])
Sign up to request clarification or add additional context in comments.

1 Comment

I think this one is the best because it is more complete and still short and precise.
2

Via https://stackabuse.com/python-check-if-variable-is-a-number/:

import numbers

variable = 5
print(isinstance(5, numbers.Number))

Comments

1

would you like to try this: (from S/O earlier posts What is the most pythonic way to check if an object is a number?)

>>> from numbers import Number
>>> from decimal import Decimal
>>> from fractions import Fraction
>>> for n in [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2']:
    print(f'{n!r:>14} {isinstance(n, Number)}')

    
             2 True
           2.0 True
Decimal('2.0') True
        (2+0j) True
Fraction(2, 1) True
           '2' False

1 Comment

Why not flag as dupe instead of copying the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.