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
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

Jacob Deppen 146 Dec 28, 2022
:sparkles: Surface lint errors during code review

✨ Linty Fresh ✨ Keep your codebase sparkly clean with the power of LINT! Linty Fresh parses lint errors and report them back to GitHub as comments on

Lyft 183 Dec 18, 2022
Typed interface stubs for Pythonista iOS

Pythonista Stubs Stubs for the Pythonista iOS API. This allows for better error detection and IDE / editor autocomplete. Installation and Usage pip in

Harold Martin 12 Jul 14, 2020
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

Łukasz Langa 103 Jun 23, 2022
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 03, 2022
coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ― John F. Woods coala provides a

coala development group 3.4k Dec 29, 2022
mypy plugin to type check Kubernetes resources

kubernetes-typed mypy plugin to dynamically define types for Kubernetes objects. Features Type checking for Custom Resources Type checking forkubernet

Artem Yarmoliuk 16 Oct 10, 2022
❄️ 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

Adam Johnson 398 Dec 23, 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 06, 2023
MonkeyType as a pytest plugin.

MonkeyType as a pytest plugin.

Marius van Niekerk 36 Nov 24, 2022
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

Peter Cock 146 Dec 15, 2022
Flake8 Type Annotation Checking

flake8-annotations flake8-annotations is a plugin for Flake8 that detects the absence of PEP 3107-style function annotations and PEP 484-style type co

S. Co1 118 Jan 05, 2023
flake8 plugin which checks that typing imports are properly guarded

flake8-typing-imports flake8 plugin which checks that typing imports are properly guarded installation pip install flake8-typing-imports flake8 codes

Anthony Sottile 50 Nov 01, 2022
A python documentation linter which checks that the docstring description matches the definition.

Darglint A functional docstring linter which checks whether a docstring's description matches the actual function/method implementation. Darglint expe

Terrence Reilly 463 Dec 31, 2022
Easy saving and switching between multiple KDE configurations.

Konfsave Konfsave is a config manager. That is, it allows you to save, back up, and easily switch between different (per-user) system configurations.

42 Sep 25, 2022
Naming Convention checker for Python

PEP 8 Naming Conventions Check your code against PEP 8 naming conventions. This module provides a plugin for flake8, the Python code checker. (It repl

Python Code Quality Authority 411 Dec 23, 2022
Tools for improving Python imports

imptools Tools for improving Python imports. Installation pip3 install imptools Overview Detailed docs import_path Import a module from any path on th

Danijar Hafner 7 Aug 07, 2022
An open-source, mini imitation of GitHub Copilot for Emacs.

Second Mate An open-source, mini imitation of GitHub Copilot using EleutherAI GPT-Neo-2.7B (via Huggingface Model Hub) for Emacs. This is a much small

Sam Rawal 238 Dec 27, 2022
OpenStack Hacking Style Checks. Mirror of code maintained at opendev.org.

Introduction hacking is a set of flake8 plugins that test and enforce the OpenStack StyleGuide Hacking pins its dependencies, as a new release of some

Mirrors of opendev.org/openstack 224 Jan 05, 2023
A framework for detecting, highlighting and correcting grammatical errors on natural language text.

Gramformer Human and machine generated text often suffer from grammatical and/or typographical errors. It can be spelling, punctuation, grammatical or

Prithivida 1.3k Jan 08, 2023