Skip to content

Improve Type Hints and Return Type Annotations in the Python Kubernetes Client #2608

@EmadDeve20

Description

@EmadDeve20

Hello everyone,

I use this library extensively in my daily work, and one issue I frequently encounter is the lack of clear type hints and return type annotations in some parts of the client.

In many cases, it is difficult to determine the exact return type of methods or object attributes without manually inspecting the source code or debugging at runtime.

For example, while working with container statuses, I wrote code like this:

pod = k8s_client.read_namespaced_pod(
    name=pod_name,
    namespace=namespace,
)

statuses: list[client.V1ContainerStatus] = (
    pod.status.container_statuses or []
)

target = next(
    (s for s in statuses if s.name == settings.TARGET_CONTAINER),
    None,
)

if not target:
    logger.warning("Container not found")
    return False

state: client.V1ContainerState = target.state

if state.running:
    logger.info("Container is running")
    return True

elif state.waiting:
    waiting: client.V1ContainerStateWaiting = state.waiting
    reason = waiting.reason

    if reason in ["OOMKilled", "Error"]:
        logger.error(f"Container waiting: {reason}")
        return False

elif state.terminated:
    terminated: client.V1ContainerStateTerminated = state.terminated
    reason = terminated.reason

    logger.error(f"Container terminated: {reason}")
    return False

One example of the confusion is this line:

statuses = pod.status.container_statuses or []

Without proper typing support, it is not immediately obvious that container_statuses is expected to be list[V1ContainerStatus] | None.

It would be very helpful if more methods and model attributes included accurate Python type hints and return type annotations.

For example:

def read_namespaced_pod(
    self,
    name,
    namespace,
    **kwargs
) -> V1Pod:
    ...

Better typing support would improve:

  • IDE autocomplete
  • Static analysis
  • Developer experience
  • Readability
  • Easier debugging and maintenance

Especially for users working with tools like:

  • mypy
  • pyright
  • pylance
  • PyCharm

If the maintainers agree that this improvement would be valuable, I would be happy to work on it and contribute a fix.

Thank you for your work on this project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featureCategorizes issue or PR as related to a new feature.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions