TensorFlow Type Stubs

2.18.0.20260408 · active · verified Wed Apr 15

types-tensorflow is a type stub package providing static type annotations for the TensorFlow library. Maintained as part of the `typeshed` project, it enables type checkers like MyPy and Pyright to analyze code using TensorFlow, improving code quality and developer tooling. This package aims to provide accurate annotations for specific TensorFlow minor versions (e.g., `~=2.18.0`). It follows a frequent release cadence, with minor and patch versions released regularly to keep pace with TensorFlow updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to write type-hinted TensorFlow code that `types-tensorflow` can then be used to check with a static type checker like `mypy` or `pyright`. It shows basic tensor creation and manipulation with Python type annotations.

import tensorflow as tf

def create_and_add_constants(val1: int, val2: int) -> tf.Tensor:
    """Creates two constant tensors from ints and adds them."""
    tensor1 = tf.constant(val1, dtype=tf.int32)
    tensor2 = tf.constant(val2, dtype=tf.int32)
    return tf.add(tensor1, tensor2)

def concatenate_tensors(tensors: list[tf.Tensor]) -> tf.Tensor:
    """Concatenates a list of tensors along axis 0."""
    return tf.concat(tensors, axis=0)

if __name__ == "__main__":
    # Example 1: Basic addition with type hints
    sum_result = create_and_add_constants(10, 20)
    print(f"Sum result (numpy value): {sum_result.numpy()}")

    # Example 2: Concatenation with explicit type hints
    tensor_a = tf.constant([1.0, 2.0], dtype=tf.float32)
    tensor_b = tf.constant([3.0, 4.0], dtype=tf.float32)
    combined_tensors = concatenate_tensors([tensor_a, tensor_b])
    print(f"Concatenated tensors (numpy value): {combined_tensors.numpy()}")

    # To run type checking:
    # 1. Save this code as `tf_example.py`.
    # 2. Install a type checker (e.g., `pip install mypy`).
    # 3. Run `mypy tf_example.py` in your terminal.
    #    Expected output: Success (no errors) if code is correctly typed.

view raw JSON →