🔍 Code Extractor

function is_number

Maturity: 27

Determines whether an object is a number or behaves like a number, with special handling for numpy types and numeric-like classes.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
1262 - 1270
Complexity:
simple

Purpose

This function provides a robust check to determine if an object is numeric, going beyond simple type checking. It handles standard Python numbers, numpy numeric types, and custom numeric-like classes (such as those from gmpy, numpy, etc.) that implement numeric protocols. It explicitly excludes numpy string types and includes backward compatibility for older versions of gmpy.

Source Code

def is_number(obj):
    if isinstance(obj, numbers.Number): return True
    elif isinstance(obj, (np.str_, np.unicode_)): return False
    # The extra check is for classes that behave like numbers, such as those
    # found in numpy, gmpy, etc.
    elif (hasattr(obj, '__int__') and hasattr(obj, '__add__')): return True
    # This is for older versions of gmpy
    elif hasattr(obj, 'qdiv'): return True
    else: return False

Parameters

Name Type Default Kind
obj - - positional_or_keyword

Parameter Details

obj: Any Python object to be tested for numeric properties. Can be a standard Python number (int, float, complex), numpy numeric type, numpy string type, or any custom object that may implement numeric protocols like __int__ and __add__, or legacy gmpy objects with qdiv method.

Return Value

Returns a boolean value: True if the object is a number or behaves like a number (implements numeric protocols), False otherwise. Specifically returns False for numpy string types (np.str_, np.unicode_) even though they might have some numeric-like methods.

Dependencies

  • numbers
  • numpy

Required Imports

import numbers
import numpy as np

Usage Example

import numbers
import numpy as np

def is_number(obj):
    if isinstance(obj, numbers.Number): return True
    elif isinstance(obj, (np.str_, np.unicode_)): return False
    elif (hasattr(obj, '__int__') and hasattr(obj, '__add__')): return True
    elif hasattr(obj, 'qdiv'): return True
    else: return False

# Test with various types
print(is_number(42))                    # True - int
print(is_number(3.14))                  # True - float
print(is_number(complex(1, 2)))         # True - complex
print(is_number(np.int64(10)))          # True - numpy int
print(is_number(np.float32(5.5)))       # True - numpy float
print(is_number(np.str_('123')))        # False - numpy string
print(is_number('123'))                 # False - regular string
print(is_number([1, 2, 3]))             # False - list
print(is_number(None))                  # False - None

Best Practices

  • This function uses duck typing to detect numeric-like objects, which is more flexible than strict type checking but may have edge cases with objects that implement __int__ and __add__ for non-numeric purposes
  • The function explicitly excludes numpy string types to prevent false positives, as they may have some numeric-like methods
  • The qdiv check is for backward compatibility with older versions of gmpy library - consider if this is still needed for your use case
  • For performance-critical code, consider caching results if checking the same types repeatedly
  • Be aware that this function will return True for custom classes that implement __int__ and __add__, which may or may not be the desired behavior depending on your use case
  • This function does not validate if the object can be successfully converted to a number, only if it appears to be numeric in nature

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function isnumeric 77.5% similar

    Determines whether a given value can be converted to a numeric type (int or float), excluding strings and boolean types.

    From: /tf/active/vicechatdev/patches/util.py
  • function is_float 71.1% similar

    A type-checking utility function that determines whether a given object is a floating-point scalar value, supporting both Python's native float type and NumPy floating-point types.

    From: /tf/active/vicechatdev/patches/util.py
  • function is_nan 66.4% similar

    A type-safe utility function that checks whether a given value is NaN (Not a Number), handling arbitrary types without raising exceptions.

    From: /tf/active/vicechatdev/patches/util.py
  • function isdatetime 63.8% similar

    Determines whether a given value (array or scalar) is a recognized datetime type, checking both NumPy datetime64 arrays and Python datetime objects.

    From: /tf/active/vicechatdev/patches/util.py
  • function is_int 60.7% similar

    Checks if an object is an integer type, supporting native Python integers, NumPy integer types, and optionally float types with integer values.

    From: /tf/active/vicechatdev/patches/util.py
← Back to Browse