Skip to content

xcheck - Runtime Validation

Runtime type validation functions that return boolean values.


xpytools.xtype.xcheck.is_int

Python
is_int(value: Any, allow_str: bool = False) -> bool

Return True if value is an integer (optionally numeric string).

Source code in xpytools/xtype/xcheck/primitives.py
Python
def is_int(value: Any, allow_str: bool = False) -> bool:
    """Return True if `value` is an integer (optionally numeric string)."""
    if isinstance(value, bool):  # bool is subclass of int
        return False
    if isinstance(value, int):
        return True
    if allow_str and isinstance(value, str):
        return value.strip().lstrip("+-").isdigit()
    return False

xpytools.xtype.xcheck.is_float

Python
is_float(value: Any, allow_str: bool = False) -> bool

Return True if value is a float (optionally numeric string).

Source code in xpytools/xtype/xcheck/primitives.py
Python
def is_float(value: Any, allow_str: bool = False) -> bool:
    """Return True if `value` is a float (optionally numeric string)."""
    if isinstance(value, float):
        return True
    if allow_str and isinstance(value, str):
        try:
            float(value.strip().replace(",", "."))  # tolerate comma separator
            return True
        except ValueError:
            return False
    return False

xpytools.xtype.xcheck.is_bool

Python
is_bool(value: Any, allow_str: bool = False) -> bool

Return True if value is a boolean or a common truthy/falsey string.

Examples:

Python Console Session
>>> is_bool(True)
True
>>> is_bool("true", allow_str=True)
True
>>> is_bool("0", allow_str=True)
True
Source code in xpytools/xtype/xcheck/primitives.py
Python
def is_bool(value: Any, allow_str: bool = False) -> bool:
    """
    Return True if value is a boolean or a common truthy/falsey string.

    Examples
    --------
    >>> is_bool(True)
    True
    >>> is_bool("true", allow_str=True)
    True
    >>> is_bool("0", allow_str=True)
    True
    """
    if isinstance(value, bool):
        return True
    if allow_str and isinstance(value, str):
        v = value.strip().lower()
        return v in {"true", "false", "1", "0", "yes", "no"}
    return False

xpytools.xtype.xcheck.is_str

Python
is_str(value: Any, non_empty: bool = False) -> bool

Return True if value is a string (optionally non-empty).

Source code in xpytools/xtype/xcheck/primitives.py
Python
def is_str(value: Any, non_empty: bool = False) -> bool:
    """Return True if value is a string (optionally non-empty)."""
    if isinstance(value, str):
        return bool(value.strip()) if non_empty else True
    return False

xpytools.xtype.xcheck.is_bytes

Python
is_bytes(value: Any) -> bool

Return True if value is a bytes or bytearray object.

Source code in xpytools/xtype/xcheck/primitives.py
Python
def is_bytes(value: Any) -> bool:
    """Return True if value is a bytes or bytearray object."""
    return isinstance(value, (bytes, bytearray))

xpytools.xtype.xcheck.is_dict

Python
is_dict(value: Any, non_empty: bool = False) -> bool

Return True if value is a dict (optionally non-empty).

Source code in xpytools/xtype/xcheck/complex.py
Python
def is_dict(value: Any, non_empty: bool = False) -> bool:
    """Return True if value is a dict (optionally non-empty)."""
    if isinstance(value, dict):
        return len(value) > 0 if non_empty else True
    return False

xpytools.xtype.xcheck.is_list_like

Python
is_list_like(value: Any, non_empty: bool = False) -> bool

Return True if value behaves like a list or tuple.

Includes Python lists, tuples, sets, and sequences excluding strings.

Source code in xpytools/xtype/xcheck/complex.py
Python
def is_list_like(value: Any, non_empty: bool = False) -> bool:
    """
    Return True if value behaves like a list or tuple.

    Includes Python lists, tuples, sets, and sequences excluding strings.
    """
    if isinstance(value, (list, tuple, set)):
        return len(value) > 0 if non_empty else True
    return False

xpytools.xtype.xcheck.is_numeric

Python
is_numeric(value: Any, allow_str: bool = False) -> bool

Return True if value is int or float (optionally numeric string).

Source code in xpytools/xtype/xcheck/complex.py
Python
def is_numeric(value: Any, allow_str: bool = False) -> bool:
    """Return True if value is int or float (optionally numeric string)."""
    return is_int(value, allow_str=allow_str) or is_float(value, allow_str=allow_str)

xpytools.xtype.xcheck.is_json

Python
is_json(value: Any) -> bool

Return True if value looks like valid JSON (str, list, dict).

Source code in xpytools/xtype/xcheck/json.py
Python
def is_json(value: Any) -> bool:
    """Return True if `value` looks like valid JSON (str, list, dict)."""
    if isinstance(value, (dict, list)):
        return True
    return False

xpytools.xtype.xcheck.is_json_like

Python
is_json_like(value: Any) -> bool

Return True if value looks like valid JSON (str, list, dict).

Source code in xpytools/xtype/xcheck/json.py
Python
def is_json_like(value: Any) -> bool:
    """Return True if `value` looks like valid JSON (str, list, dict)."""
    if is_json(value):
        return True
    if isinstance(value, str):
        try:
            json.loads(value)
            return True
        except Exception:
            return False
    return False

xpytools.xtype.xcheck.is_datetime

Python
is_datetime(value: Any) -> bool

Return True if value is datetime.

Source code in xpytools/xtype/xcheck/datetime.py
Python
def is_datetime(value: Any) -> bool:
    """
    Return True if value is datetime.
    """
    if isinstance(value, datetime):
        return True
    return False

xpytools.xtype.xcheck.is_datetime_like

Python
is_datetime_like(value: Any) -> bool

Return True if value looks like a datetime or ISO 8601 timestamp string.

Source code in xpytools/xtype/xcheck/datetime.py
Python
def is_datetime_like(value: Any) -> bool:
    """
    Return True if value looks like a datetime or ISO 8601 timestamp string.
    """
    if is_datetime(value):
        return True
    if isinstance(value, str):
        try:
            datetime.fromisoformat(value.replace("Z", "+00:00"))
            return True
        except Exception:
            return False
    return False

xpytools.xtype.xcheck.is_none

Python
is_none(value: Any) -> bool

Return True if value represents a null or missing value.

Includes: - None - float('nan'), numpy.nan, numpy.float64(nan) - pandas.NA, pandas.NaT, pandas.NAN - string representations: 'nan', 'none', 'null', 'na', 'n/a', 'n a', etc.

Source code in xpytools/xtype/xcheck/null.py
Python
def is_none(value: Any) -> bool:
    """
    Return True if `value` represents a null or missing value.

    Includes:
      - None
      - float('nan'), numpy.nan, numpy.float64(nan)
      - pandas.NA, pandas.NaT, pandas.NAN
      - string representations: 'nan', 'none', 'null', 'na', 'n/a', 'n a', etc.
    """
    # --- 1. Fast explicit None ---
    if value is None:
        return True

    # NaN-like
    try:
        if value != value:
            return True
    except Exception:
        pass

    # NumPy / pandas
    try:
        import numpy as np
        if value is np.nan:
            return True
        if isinstance(value, np.generic):
            try:
                if np.isnan(value):
                    return True
            except Exception:
                pass
    except ImportError:
        pass

    try:
        import pandas as pd
        if getattr(pd, "isna", None):
            try:
                if pd.isna(value):
                    return True
            except Exception:
                pass
    except ImportError:
        pass

    # String null-like
    if isinstance(value, str):
        v = value.strip().lower()
        compact = v.replace(" ", "").replace("-", "").replace(".", "")

        null_like = {
                "", "none", "null", "nil",
                "na", "n/a", "n.a", "n a", "n-a",
                "nan", "nann", "n.a.", "notapplicable", "missing", "void"
                }

        if v in null_like or compact in null_like:
            return True

    return False

xpytools.xtype.xcheck.is_empty

Functions:

Name Description
is_empty

Returns True if the object is empty (has no values).

is_empty

Python
is_empty(obj: Union[Any, 'pdDataFrame']) -> bool

Returns True if the object is empty (has no values). Works for DataFrames, Series, lists, dicts, sets, and strings.

Source code in xpytools/xtype/xcheck/is_empty.py
Python
def is_empty(obj: Union[Any, "pdDataFrame"]) -> bool:
    """
    Returns True if the object is empty (has no values).
    Works for DataFrames, Series, lists, dicts, sets, and strings.
    """
    if obj is None:
        return True
    try:
        if hasattr(obj, "empty"):
            return getattr(obj, "empty")
        if hasattr(obj, "__len__"):
            return len(obj) == 0
        return not bool(obj)
    except Exception:
        return False

xpytools.xtype.xcheck.is_uuid

Python
is_uuid(value: Any) -> bool

Return True if value is a valid UUID string or UUID instance.

Source code in xpytools/xtype/xcheck/uuid.py
Python
def is_uuid(value: Any) -> bool:
    """Return True if `value` is a valid UUID string or UUID instance."""
    if isinstance(value, UUID):
        return True
    return False

xpytools.xtype.xcheck.is_uuid_like

Python
is_uuid_like(value: Any) -> bool

Return True if value looks like a valid UUID.

Source code in xpytools/xtype/xcheck/uuid.py
Python
def is_uuid_like(value: Any) -> bool:
    """Return True if `value` looks like a valid UUID."""
    try:
        if is_uuid(value):
            return True
        UUIDLike(value)
        return True
    except Exception:
        return False

xpytools.xtype.xcheck.is_base64

Python
is_base64(data: str) -> bool

Heuristically xcheck if a string is valid Base64-encoded data. Returns True only if: • it's a str of reasonable length, • matches base64 charset, • and decodes successfully without error.

Source code in xpytools/xtype/xcheck/base64.py
Python
def is_base64(data: str) -> bool:
    """
    Heuristically xcheck if a string is valid Base64-encoded data.
    Returns True only if:
      • it's a str of reasonable length,
      • matches base64 charset,
      • and decodes successfully without error.
    """
    if not isinstance(data, str) or len(data) < 16:  # short strings are rarely base64 images
        return False

    # strip any data URI prefix
    if "," in data and data.strip().startswith("data:"):
        data = data.split(",", 1)[1]

    data = data.strip()

    # must be multiple of 4 chars (Base64 requirement)
    if len(data) % 4 != 0:
        return False

    # must match base64 charset (A–Z, a–z, 0–9, +, /, =)
    if not _BASE64_RE.match(data):
        return False

    # try decode / re-encode consistency xcheck
    try:
        decoded = base64.b64decode(data, validate=True)
        # re-encode and see if it matches (ignoring trailing padding differences)
        reencoded = base64.b64encode(decoded).decode().rstrip("=")
        return data.rstrip("=") == reencoded
    except Exception:
        return False

xpytools.xtype.xcheck.is_df

Python
is_df(obj: Any) -> bool

Return True if obj looks like a pandas DataFrame.

Source code in xpytools/xtype/xcheck/dataframe.py
Python
def is_df(obj: Any) -> bool:
    """Return True if `obj` looks like a pandas DataFrame."""
    try:
        from pandas import DataFrame as pdDataFrame
    except ImportError:
        return False

    return isinstance(obj, pdDataFrame)