I find myself using this little util a lot. It’s essentially a merge of Python’s ‘isinstance’ function and JS’ ‘instanceof’ operator. Perhaps you’ll find it useful too.
from anvil.js.window import Function as _Function, Object as _Object
from anvil.js import new as _new
_isInstance = _new(_Function, "value", "ref", "return value instanceof ref;")
def is_instance_of(value, ref) -> bool:
"""Special hybrid of Python's 'isinstance' function and JS' 'instanceof' operator.
Interprets 'int' as excluding Booleans."""
if not isinstance(ref, tuple):
ref = (ref,)
for r in ref:
if isinstance(r, type):
if r is int:
# Ensure that True and False are not interpreted as 'int' (which they are in Python)
if isinstance(value, int) and not isinstance(value, bool):
return True
else:
if isinstance(value, r):
return True
elif _isInstance(r, _Object):
if _isInstance(value, r):
return True
else:
raise TypeError(
f"Invalid type, '{type(r)}' for {r}. Expected instance of 'type' or JS object."
)
return False