mypy plugin to type check Kubernetes resources

Overview

mypy logo

kubernetes-typed

Build status Checked with mypy

mypy plugin to dynamically define types for Kubernetes objects.

Features

Installation

Install with pip:

pip install kubernetes-typed

Versioning

This package follows kubernetes client versioning approach. MAJOR.MINOR parts of version will match client version for which stubs were generated, and PATCH version will be stub or plugin specific updates.

Custom Resource Definitions

Add type checks for Custom Resource Definition spec given its definition in yaml file .

  1. Configure mypy to use crd_typed plugin:
[mypy]

plugins = crd_typed.plugin
  1. Import CustomResource
from crd_type import CustomResource
  1. Annotate your variables:
resource: CustomResource["relative/path/to/crd.yaml"]

You can get type definition for different parts of crd:

  • Get TypeDict definition for custom resource body:

    from crd_type import CustomResource
    
    resource: CustomResource["relative/path/to/crd.yaml"]
  • Get definition only for resource spec:

    from crd_type import CustomResource
    
    resource: CustomResource["relative/path/to/crd.yaml", "spec"]
  • Get definition for nested spec item, if that item is type object or array:

    from crd_type import CustomResource
    
    resource: CustomResource["relative/path/to/crd.yaml", "spec", "some_property"]
  • Get definition for array item, if that is array of objects, via items key:

    from crd_type import CustomResource
    
    resource: CustomResource["relative/path/to/crd.yaml", "spec", "some_array_of_objects", "items"]

Limitations

  • CRDs that use additionalProperties are not supported.
  • CRDs can define multiple versions, currently only first one will be used
  • Custom attributes like x-kubernetes-int-or-string, x-kubernetes-embedded-resource, are not supported

Kubernetes Python Client types

This package provides basic type stubs for kubernetes python client out of the box.

To enable full type checking for classes use provided kubernetes_typed plugin. This plugin requires kubernetes, you can require it during installation like this:

pip install kubernetes-typed[client]

Configure mypy to use it and it will automatically type check classes from kubernetes.client:

[mypy]

plugins = kubernetes_typed.plugin

Kubernetes Python Client Models Dict Types

If you want to type check resource dicts instead of classes, you can use generated TypedDicts provided by this package.

To do this for any model class in kubernetes.client append its name with Dict, and import it from kubernetes_type.client

For example:

kubernetes.client.V1Pod -> kubernetes_typed.client.V1PodDict

from kubernetes.client.api import core_v1_api

from kubernetes_typed.client import V1PodDict

api_instance = core_v1_api.CoreV1Api()

pod_manifest: V1PodDict = {
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {"name": "test-pod"},
    "spec": {
        "containers": [
            {
                "image": "nginx",
                "name": "nginx",
            },
        ],
    },
}

api_instance.create_namespaced_pod(body=pod_manifest, namespace='default')

Limitations

  • Kubernetes client api functions are currently not covered by stubs, so you might get Call to untyped function errors. Check mypy config doc on how to disable separate warnings.
You might also like...
โ„๏ธ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

flake8 plugin that integrates isort

Flake8 meet isort Use isort to check if the imports on your python files are sorted the way you expect. Add an .isort.cfg to define how you want your

Flake8 plugin to find commented out or dead code
Flake8 plugin to find commented out or dead code

flake8-eradicate flake8 plugin to find commented out (or so called "dead") code. This is quite important for the project in a long run. Based on eradi

A Pylint plugin to analyze Flask applications.

pylint-flask About pylint-flask is Pylint plugin for improving code analysis when editing code using Flask. Inspired by pylint-django. Problems pylint

flake8 plugin to run black for checking Python coding style

flake8-black Introduction This is an MIT licensed flake8 plugin for validating Python code style with the command line code formatting tool black. It

A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

flake8 plugin to catch useless `assert` statements

flake8-useless-assert flake8 plugin to catch useless assert statements Download or install on the PyPI page Violations Code Description Example ULA001

MagTape is a Policy-as-Code tool for Kubernetes that allows for evaluating Kubernetes resources against a set of defined policies to inform and enforce best practice configurations.
MagTape is a Policy-as-Code tool for Kubernetes that allows for evaluating Kubernetes resources against a set of defined policies to inform and enforce best practice configurations.

MagTape is a Policy-as-Code tool for Kubernetes that allows for evaluating Kubernetes resources against a set of defined policies to inform and enforce best practice configurations. MagTape includes variable policy enforcement, notifications, and targeted metrics.

Mypy static type checker plugin for Pytest

pytest-mypy Mypy static type checker plugin for pytest Features Runs the mypy static type checker on your source files as part of your pytest test run

Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Kubernetes shell: An integrated shell for working with the Kubernetes
Kubernetes shell: An integrated shell for working with the Kubernetes

kube-shell Kube-shell: An integrated shell for working with the Kubernetes CLI Under the hood kube-shell still calls kubectl. Kube-shell aims to provi

Google Kubernetes Engine (GKE) with a Snyk Kubernetes controller installed/configured for Snyk App
Google Kubernetes Engine (GKE) with a Snyk Kubernetes controller installed/configured for Snyk App

Google Kubernetes Engine (GKE) with a Snyk Kubernetes controller installed/configured for Snyk App This example provisions a Google Kubernetes Engine

Django-Kubernetes - Learn how to deploy a docker-based Django application into a Kubernetes cluster into production on DigitalOcean
Helperpod - A CLI tool to run a Kubernetes utility pod with pre-installed tools that can be used for debugging/testing purposes inside a Kubernetes cluster

Helperpod is a CLI tool to run a Kubernetes utility pod with pre-installed tools that can be used for debugging/testing purposes inside a Kubernetes cluster.

A plugin for flake8 integrating Mypy.

flake8-mypy NOTE: THIS PROJECT IS DEAD It was created in early 2017 when Mypy performance was often insufficient for in-editor linting. The Flake8 plu

A Simple script to hunt unused Kubernetes resources.

K8SPurger A Simple script to hunt unused Kubernetes resources. Release History Release 0.3 Added Ingress Added Services Account Adding RoleBindding Re

An AWS Pentesting tool that lets you use one-liner commands to backdoor an AWS account's resources with a rogue AWS account - or share the resources with the entire internet ๐Ÿ˜ˆ
An AWS Pentesting tool that lets you use one-liner commands to backdoor an AWS account's resources with a rogue AWS account - or share the resources with the entire internet ๐Ÿ˜ˆ

An AWS Pentesting tool that lets you use one-liner commands to backdoor an AWS account's resources with a rogue AWS account - or share the resources with the entire internet ๐Ÿ˜ˆ

Participants of Bertelsmann Technology Scholarship created an awesome list of resources and they want to share it with the world, if you find illegal resources please report to us and we will remove.

Participants of Bertelsmann Technology Scholarship created an awesome list of resources and they want to share it with the world, if you find illegal

Comments
  • upper bound on mypy dependency

    upper bound on mypy dependency

    The setup.py file declares an upper bound on the mypy dependency https://github.com/gordonbondon/kubernetes-typed/blob/82995b008daf551a4fe11660018d9c08c69f9e6e/setup.py#L77 Is there a particular reason for that? Newer versions of mypy often come with good bugfixes, I'd like to use this package with a newer mypy version, if possible.

    opened by tgpfeiffer 1
  • Circular references

    Circular references

    Hi there,

    I'm getting the below error when using this:

    from kubernetes_typed.client import V1PodDict
    
    ImportError: cannot import name 'AdmissionregistrationV1ServiceReferenceDict' from partially initialized module 'kubernetes_typed.client' (most likely due to a circular import) (/home/user/repos/xxx/k8s-monitor/.venv/lib/python3.8/site-packages/kubernetes_typed/client/__init__.py)
    
    opened by callum-p 1
  • Add new dynamic class CustomResourceDict with version support

    Add new dynamic class CustomResourceDict with version support

    Current approach with CustomResource["relative/path/to/crd.yaml", "spec", "some_property"] is limited to having only one definition/version in crd file and its impossible to extend with new options. Returned errors always mention TypedDict('Jsonschema') which is not userfriendly.

    Instead, we should use get_dynamic_class_hook https://github.com/python/mypy/blob/3acbf3fe78a61c19ff96754233ada453472004c4/mypy/plugin.py#L692-L705 to provide more options while creating custom resource type definition. Possible syntax:

    MyResource = CustomResourceDict(
        definition_path="/path/to/crd.yaml",
        property_path: ["spec", "some_property"]
        group: "myapi.io",
        version: "v1",
        kind: "MyResource"
    )
    

    First iteration should include these features:

    • [ ] CustomResourceDict dynamic hook
    • [ ] Handle multiple versions per CustomResourceDefinition
    • [ ] Handle multiple definitions per file
    • [ ] Set TypeDict name from kind

    Similar to https://github.com/lovasoa/marshmallow_dataclass/blob/513e8bfc0dcef02314180790486cea3c04f65178/marshmallow_dataclass/mypy.py

    enhancement 
    opened by gordonbondon 0
Releases(v18.20.0)
Owner
Artem Yarmoliuk
dealing with complex codes ๐Ÿ‡บ๐Ÿ‡ฆ ๐Ÿ‡ญ๐Ÿ‡ฐ
Artem Yarmoliuk
open source tools to generate mypy stubs from protobufs

mypy-protobuf: Generate mypy stub files from protobuf specs We just released a new major release mypy-protobuf 2. on 02/02/2021! It includes some back

Dropbox 527 Jan 3, 2023
Performant type-checking for python.

Pyre is a performant type checker for Python compliant with PEP 484. Pyre can analyze codebases with millions of lines of code incrementally โ€“ providi

Facebook 6.2k Jan 4, 2023
A static type analyzer for Python code

pytype - ?? โœ” Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 4k Dec 31, 2022
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a โ€œwatchโ€ mode and performs fas

Microsoft 9.2k Jan 3, 2023
Unbearably fast O(1) runtime type-checking in pure Python.

Look for the bare necessities, the simple bare necessities. Forget about your worries and your strife. โ€” The Jungle Book.

beartype 1.4k Jan 1, 2023
Tool to check the completeness of MANIFEST.in for Python packages

check-manifest Are you a Python developer? Have you uploaded packages to the Python Package Index? Have you accidentally uploaded broken packages with

Marius Gedminas 270 Dec 26, 2022
Check for python builtins being used as variables or parameters

Flake8 Builtins plugin Check for python builtins being used as variables or parameters. Imagine some code like this: def max_values(list, list2):

Gil Forcada Codinachs 98 Jan 8, 2023
Flake8 extension to provide force-check option

flake8-force Flake8 extension to provide force-check option. When this option is enabled, flake8 performs all checks even if the target file cannot be

Kenichi Maehashi 9 Oct 29, 2022
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 869 Dec 30, 2022
Pylint plugin for improving code analysis for when using Django

pylint-django About pylint-django is a Pylint plugin for improving code analysis when analysing code using Django. It is also used by the Prospector t

Python Code Quality Authority 544 Jan 6, 2023