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 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
Flake8 plugin to validate annotations complexity

flake8-annotations-complexity An extension for flake8 to report on too complex type annotations. Complex type annotations often means bad annotations

BestDoctor 41 Dec 28, 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 03, 2023
Plugin for mypy to support zope.interface

Plugin for mypy to support zope.interface The goal is to be able to make zope interfaces to be treated as types in mypy sense. Usage Install both mypy

Shoobx 36 Oct 29, 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
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 simple program which checks Python source files for errors

Pyflakes A simple program which checks Python source files for errors. Pyflakes analyzes programs and detects various errors. It works by parsing the

Python Code Quality Authority 1.2k Dec 30, 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
Flashcards - A flash card application with 2 optional command line arguments

Flashcards A flash card application with 2 optional command line arguments impor

Özgür Yildirim 2 Jul 15, 2022
🦆 Better duck-typing with mypy-compatible extensions to Protocol

🦆 Quacks If it walks like a duck and it quacks like a duck, then it must be a duck Thanks to PEP544, Python now has protocols: a way to define duck t

Arie Bovenberg 9 Nov 14, 2022
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
Flake8 plugin for managing type-checking imports & forward references

flake8-type-checking Lets you know which imports to put in type-checking blocks. For the imports you've already defined inside type-checking blocks, i

snok 67 Dec 16, 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
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
It's not just a linter that annoys you!

README for Pylint - https://pylint.pycqa.org/ Professional support for pylint is available as part of the Tidelift Subscription. Tidelift gives softwa

Python Code Quality Authority 4.4k Jan 04, 2023
MyPy types for WSGI applications

WSGI Types for Python This is an attempt to bring some type safety to WSGI applications using Python's new typing features (TypedDicts, Protocols). It

Blake Williams 2 Aug 18, 2021
Utilities for pycharm code formatting (flake8 and black)

Pycharm External Tools Extentions to Pycharm code formatting tools. Currently supported are flake8 and black on a selected code block. Usage Flake8 [P

Haim Daniel 13 Nov 03, 2022
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
Pymxs, the 3DsMax bindings of Maxscript to Python doesn't come with any stubs

PyMXS Stubs generator What Pymxs, the 3DsMax bindings of Maxscript to Python doe

Frieder Erdmann 19 Dec 27, 2022
Collection of awesome Python types, stubs, plugins, and tools to work with them.

Awesome Python Typing Collection of awesome Python types, stubs, plugins, and tools to work with them. Contents Static type checkers Dynamic type chec

TypedDjango 1.2k Jan 04, 2023