Kubernetes Type Stubs (Elephant Fork)

35.0.0.post1 · active · verified Thu Apr 16

This library provides type stubs for the official Kubernetes Python API client. It is an actively maintained fork of the original `kubernetes-stubs` package, offering static type checking support for projects using the `kubernetes` client. The current version is 35.0.0.post1, with a frequent release cadence aimed at keeping pace with upstream `kubernetes` client updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how `kubernetes-stubs-elephant-fork` provides type hints for code that uses the `kubernetes` client library. The stubs are automatically picked up by type checkers like MyPy, without requiring direct imports from the stub package. The `if __name__ == "__main__"` block provides a runnable example requiring Kubernetes connectivity.

import os
from kubernetes import client, config
from typing import TYPE_CHECKING

# This function will only execute at runtime, not during type checking
if not TYPE_CHECKING:
    # Load Kubernetes configuration
    # For local development, e.g., ~/.kube/config
    try:
        config.load_kube_config(context=os.environ.get('KUBE_CONTEXT', ''))
    except config.config_exception.ConfigException:
        # Fallback for CI/CD or in-cluster
        config.load_incluster_config()

def get_pod_names(namespace: str) -> list[str]:
    # The type checker uses kubernetes-stubs-elephant-fork here
    v1: client.CoreV1Api = client.CoreV1Api()
    
    # The return type of list_namespaced_pod is typed by the stubs
    pods_list = v1.list_namespaced_pod(namespace=namespace)
    
    names: list[str] = []
    for pod in pods_list.items:
        if pod.metadata and pod.metadata.name:
            names.append(pod.metadata.name)
    return names

if __name__ == "__main__":
    # Example runtime usage (requires a running Kubernetes cluster/config)
    try:
        # Replace 'default' with your target namespace or use env var
        target_namespace = os.environ.get('KUBE_NAMESPACE', 'default')
        pod_names = get_pod_names(target_namespace)
        print(f"Pods in '{target_namespace}' namespace: {pod_names}")
    except Exception as e:
        print(f"Could not list pods (is Kubernetes configured?): {e}")

# To type-check this file:
# 1. pip install mypy kubernetes kubernetes-stubs-elephant-fork
# 2. mypy quickstart.py

view raw JSON →