U UniCore Community Public content rendered for search, speed, and sharing

Documentation

Type Checking

Type guard helpers and validation utilities.

Functions to check and validate types in your code.

is_string()

Checks if a value is a string

Implementation

Uses isinstance with str type

Example

UniCoreFW.is_string("hello")

Expected output: True

Source Code

def is_string(obj):
    return isinstance(obj, str)

is_number()

Checks if a value is a number (int or float)

Implementation

Uses isinstance with numeric types tuple

Example

UniCoreFW.is_number(42)

Expected output: True

Source Code

def is_number(obj):
    return isinstance(obj, (int, float))

is_array()

Checks if a value is a list

Implementation

Uses isinstance with list type

Example

UniCoreFW.is_array([1, 2, 3])

Expected output: True

Source Code

def is_array(obj):
    return isinstance(obj, list)

is_object()

Checks if a value is a dictionary

Implementation

Uses isinstance with dict type

Example

UniCoreFW.is_object({"name": "John"})

Expected output: True

Source Code

def is_object(obj):
    return isinstance(obj, dict)

is_function()

Checks if a value is callable

Implementation

Uses Python's callable() function

Example

UniCoreFW.is_function(lambda x: x)

Expected output: True

Source Code

def is_function(obj):
    return callable(obj)

is_boolean()

Checks if a value is a boolean

Implementation

Uses isinstance with bool type

Example

UniCoreFW.is_boolean(True)

Expected output: True

Source Code

def is_boolean(obj):
    return isinstance(obj, bool)

is_date()

Checks if a value is a date object

Implementation

Uses isinstance with datetime.date

Example

UniCoreFW.is_date(datetime.date(2023, 1, 1))

Expected output: True

Source Code

def is_date(obj):
    from datetime import date
    return isinstance(obj, date)

is_reg_exp()

Checks if a value is a regular expression

Implementation

Uses isinstance with re.Pattern

Example

UniCoreFW.is_reg_exp(re.compile("pattern"))

Expected output: True

Source Code

def is_reg_exp(obj):
    return isinstance(obj, re.Pattern)

is_error()

Checks if a value is an exception

Implementation

Uses isinstance with Exception base class

Example

UniCoreFW.is_error(ValueError("test"))

Expected output: True

Source Code

def is_error(obj):
    return isinstance(obj, Exception)

is_null()

Checks if a value is None

Implementation

Uses direct comparison with None

Example

UniCoreFW.is_null(None)

Expected output: True

Source Code

def is_null(obj):
    return obj is None

is_undefined()

Checks if a value is None (Python equivalent of undefined)

Implementation

Uses direct comparison with None

Example

UniCoreFW.is_undefined(None)

Expected output: True

Source Code

def is_undefined(obj):
    return obj is None

is_finite()

Checks if a value is a finite number

Implementation

Uses math.isfinite after type checking

Example

UniCoreFW.is_finite(42)

Expected output: True

Source Code

def is_finite(obj):
    from math import isfinite
    return isinstance(obj, (int, float)) and isfinite(obj)

is_nan()

Checks if a value is NaN

Implementation

Uses math.isnan after type checking

Example

UniCoreFW.is_nan(float('nan'))

Expected output: True

Source Code

def is_nan(obj):
    from math import isnan
    return isinstance(obj, float) and isnan(obj)

is_map()

Checks if a value is a map (dictionary in Python)

Implementation

Uses isinstance with dict type

Example

UniCoreFW.is_map({"key": "value"})

Expected output: True

Source Code

def is_map(obj):
    return isinstance(obj, dict)

is_set()

Checks if a value is a set

Implementation

Uses isinstance with set type

Example

UniCoreFW.is_set({1, 2, 3})

Expected output: True

Source Code

def is_set(obj):
    return isinstance(obj, set)

is_arguments()

Checks if a value is an arguments object (tuple in Python)

Implementation

Uses isinstance with tuple type

Example

UniCoreFW.is_arguments((1, 2, 3))

Expected output: True

Source Code

def is_arguments(obj):
    return isinstance(obj, tuple)

is_array_buffer()

Checks if a value is an array buffer (array.array in Python)

Implementation

Uses isinstance with array.array type

Example

UniCoreFW.is_array_buffer(array.array('i', [1, 2, 3]))

Expected output: True

Source Code

def is_array_buffer(obj):
    import array
    return isinstance(obj, array.array)

is_data_view()

Checks if a value is a DataView (memoryview in Python)

Implementation

Uses isinstance with memoryview type

Example

UniCoreFW.is_data_view(memoryview(b'abc'))

Expected output: True

Source Code

def is_data_view(obj):
    return isinstance(obj, memoryview)

is_typed_array()

Checks if a value is a typed array

Implementation

Uses isinstance with array.array

Example

UniCoreFW.is_typed_array(array.array('i', [1, 2, 3]))

Expected output: True

Source Code

def is_typed_array(obj):
    from array import array
    return isinstance(obj, array)

is_weak_map()

Checks if a value is a WeakMap

Implementation

Uses isinstance with WeakKeyDictionary

Example

UniCoreFW.is_weak_map(weakref.WeakKeyDictionary())

Expected output: True

Source Code

def is_weak_map(obj):
    from weakref import WeakKeyDictionary
    return isinstance(obj, WeakKeyDictionary)

is_weak_set()

Checks if a value is a WeakSet

Implementation

Uses isinstance with WeakSet

Example

UniCoreFW.is_weak_set(weakref.WeakSet())

Expected output: True

Source Code

def is_weak_set(obj):
    from weakref import WeakSet
    return isinstance(obj, WeakSet)

is_element()

Checks if a value is a DOM element (ElementTree.Element in Python)

Implementation

Uses isinstance with Element, with exception handling for import

Example

UniCoreFW.is_element(ElementTree.Element('tag'))

Expected output: True

Source Code

def is_element(obj):
    try:
        from xml.etree.ElementTree import Element
        return isinstance(obj, Element)
    except ImportError:
        return False

is_empty()

Checks if a value is empty

Implementation

Checks various types for emptiness

Example

UniCoreFW.is_empty([])

Expected output: True

Source Code

def is_empty(obj):
    if obj is None:
        return True
    if hasattr(obj, "__len__"):
        return len(obj) == 0
    if hasattr(obj, "__iter__"):
        return not any(True for _ in obj)
    return False

is_symbol()

Checks if a value is a symbol-like object in Python

Implementation

Checks for various module, function, and class types

Example

UniCoreFW.is_symbol(lambda: None)

Expected output: True

Source Code

def is_symbol(obj):
    return isinstance(
        obj, (types.ModuleType, types.BuiltinFunctionType, types.FunctionType, type)
    )

is_equal()

Deep equality with cycle handling and fast paths.

Implementation

Semantics: - Requires exact same type (type(a) is type(b)), like your original. - dict/Mapping: keys must match; values compared deeply. - list/tuple/Sequence (not str/bytes/bytearray): order matters. - set/frozenset/Set: order doesn't matter (direct equality). - Other types fall back to ==. - No special-casing for NaN (NaN != NaN), preserving original behavior.

Complexity: O(N) in the total number of elements visited across both structures.

Args:
    obj1: First object to compare
    obj2: Second object to compare

Returns:
    True if objects are deeply equal, False otherwise

Example

is_equal([1, 2, 3], [1, 2, 3])

Expected output: True

Source Code

def is_equal(obj1: Any, obj2: Any) -> bool:
    if obj1 is obj2:
        return True
    if type(obj1) is not type(obj2):
        return False

    # Fast-path for common immutables
    if isinstance(obj1, (int, float, str, bool, type(None), bytes, bytearray, memoryview, range)):
        return obj1 == obj2

    # Iterative DFS with cycle detection on (id(a), id(b)) pairs
    seen: set[Tuple[int, int]] = set()
    stack: List[Tuple[Any, Any]] = [(obj1, obj2)]

    while stack:
        a, b = stack.pop()
        if a is b:
            continue
        if type(a) is not type(b):
            return False

        pid = (id(a), id(b))
        if pid in seen:
            continue
        seen.add(pid)

        # Re-check fast-path for inner elements
        if isinstance(a, (int, float, str, bool, type(None), bytes, bytearray, memoryview, range)):
            if a != b:
                return False
            continue

        # Mappings: keys must match; push value pairs
        if isinstance(a, Mapping):
            # Quick reject on size or key set mismatch
            if len(a) != len(b):  # type: ignore[arg-type]
                return False
            # Using mapping view equality is O(n) and order-insensitive
            if a.keys() != b.keys():  # type: ignore[arg-type]
                return False
            # Compare corresponding values
            for k in a.keys():
                stack.append((a[k], b[k]))  # type: ignore[index]
            continue

        # Sets (unordered)
        if isinstance(a, Set) and not isinstance(a, (str, bytes, bytearray)):
            # Direct set equality is fine
            if a != b:  # type: ignore[comparison-overlap]
                return False
            continue

        # Sequences (ordered) – but exclude string/bytes-like
        if isinstance(a, Sequence) and not isinstance(a, (str, bytes, bytearray)):
            if len(a) != len(b):  # type: ignore[arg-type]
                return False
            # Push in order so mismatches are caught early
            # (iterate by index to avoid zip generator overhead)
            for i in range(len(a)):  # type: ignore[arg-type]
                stack.append((a[i], b[i]))  # type: ignore[index]
            continue

        # Fallback for everything else (custom objects, etc.)
        if a != b:
            return False

    return True