xcheck - Runtime Validation¶
Runtime type validation functions that return boolean values.
xpytools.xtype.xcheck.is_int
¶
Return True if value is an integer (optionally numeric string).
Source code in xpytools/xtype/xcheck/primitives.py
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
¶
Return True if value is a float (optionally numeric string).
Source code in xpytools/xtype/xcheck/primitives.py
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
¶
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
Source code in xpytools/xtype/xcheck/primitives.py
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
¶
Return True if value is a string (optionally non-empty).
xpytools.xtype.xcheck.is_bytes
¶
xpytools.xtype.xcheck.is_dict
¶
Return True if value is a dict (optionally non-empty).
xpytools.xtype.xcheck.is_list_like
¶
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
xpytools.xtype.xcheck.is_numeric
¶
Return True if value is int or float (optionally numeric string).
xpytools.xtype.xcheck.is_json
¶
xpytools.xtype.xcheck.is_json_like
¶
Return True if value looks like valid JSON (str, list, dict).
xpytools.xtype.xcheck.is_datetime
¶
xpytools.xtype.xcheck.is_datetime_like
¶
Return True if value looks like a datetime or ISO 8601 timestamp string.
Source code in xpytools/xtype/xcheck/datetime.py
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
¶
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
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
¶
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
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
¶
xpytools.xtype.xcheck.is_uuid_like
¶
xpytools.xtype.xcheck.is_base64
¶
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
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
¶
Return True if obj looks like a pandas DataFrame.