Skip to content
/ keyof Public

Mypy plugin for static type checking of TypedDict keys inspired by TypeScript's keyof type operator.

License

Notifications You must be signed in to change notification settings

ViliamV/keyof

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

KeyOf

Mypy plugin for static type checking of TypedDict keys inspired by TypeScript's keyof type operator.

Requirements

  • python>=3.11
  • mypy>=1.0.1

Installation

pip install keyof

Mypy plugin

Add keyof.mypy_plugin to the list of plugins in your mypy config file (for example pyproject.toml)

[tool.mypy]
plugins = ["keyof.mypy_plugin"]

Features

  • KeyOf, RequiredKeyOf, and NotRequiredKeyOf types

  • ✅ Supports inheritance

  • ✅ Plays nicely with other types, e.g. KeyOf[Foo] | Literal["bar"]

  • ✅ Compatibility module for Pylance and Pyright

  • ✅ Zero dependencies

  • ❌ Generic TypeVar arguments

Usage

from typing import TypedDict

from keyof import KeyOf


class Data(TypedDict):
    version: int
    command: str


def get_data(data: Data, key: KeyOf[Data]) -> int | str:
    return data[key]


data = Data(version=1, command="foo")

get_data(data, "version")  # OK

get_data(data, "foo")
# mypy catches the error:
# error: Argument 2 to "get_data" has incompatible type "Literal['foo']"; expected "Literal['version', 'command']"

Usage with other type checkers

Since Pylance and Pyright don't support plugins and cannot correctly handle subclassing of Any (new in Python 3.11) there is compatibility module keyof.compat that exports the same types but they are only TypeAlias for Any.

About

Mypy plugin for static type checking of TypedDict keys inspired by TypeScript's keyof type operator.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages