torch.is_tensor
function is_tensor(obj: unknown): obj is TensorClassChecks whether the given object is a Tensor instance.
Type-safe check to distinguish Tensor objects from other types (arrays, objects, primitives). Returns a TypeScript type guard, narrowing the type to Tensor if true. Useful for:
- Type checking: Runtime validation of tensor objects
- API safety: Checking arguments before tensor operations
- Type guards: Narrowing types for better TypeScript type checking
- Conditional logic: Handling different input types appropriately
- Serialization: Distinguishing tensors from regular data when serializing models
This is a runtime instanceof check, so it safely handles any input type without errors. Returns true only for actual Tensor instances, not for array-like objects or tensor-like objects.
- Type guard: Narrows type in TypeScript for better checking
- Safe: Works on any input type, never throws
- Instanceof check: Uses JavaScript instanceof for accuracy
- Subclasses: Returns true for Tensor subclasses too
- Runtime only: No compile-time validation, purely runtime check
- Does not validate shape: Only checks if object is a Tensor, not its contents
- Proxy/wrappers: Returns false for tensor-like objects that aren't actual Tensors
Parameters
objunknown- Any object or value to check
Returns
obj is TensorClass– True if obj is a Tensor instance, false otherwise. Acts as TypeScript type guard.Examples
// Basic type checking
const x = torch.tensor([1, 2, 3]);
torch.is_tensor(x); // true
torch.is_tensor([1, 2, 3]); // false
torch.is_tensor(42); // false
torch.is_tensor(null); // false// Type guard for function arguments
function processInput(x: unknown) {
if (torch.is_tensor(x)) {
// TypeScript now knows x is a Tensor
const result = x.sum();
return result;
} else {
// Handle non-tensor input
const tensor = torch.tensor(x);
return tensor.sum();
}
}// Filtering mixed collections
const items = [torch.randn([2]), "not a tensor", torch.ones([3])];
const tensors = items.filter(torch.is_tensor);
// tensors is [Tensor, Tensor]See Also
- PyTorch torch.is_tensor()
- is_floating_point - Check tensor dtype
- Tensor - Tensor class being checked