Skip to main content

Runtime type checking decorators for function arguments

Project description

philiprehberger-type-guard

Tests PyPI version License

Runtime type checking decorators for function arguments.

Installation

pip install philiprehberger-type-guard

Usage

Basic Usage

from philiprehberger_type_guard import guard

@guard
def greet(name: str, times: int = 1) -> str:
    return name * times

greet("hello", 3)     # Works fine
greet(123, 3)          # Raises TypeGuardError

Generic Types

@guard
def process(items: list[int], lookup: dict[str, float]):
    ...

process([1, 2, 3], {"a": 1.0})  # OK
process(["a"], {})               # TypeGuardError

Union Types

@guard
def flexible(value: int | str | None):
    ...

flexible(42)     # OK
flexible("hi")   # OK
flexible(None)   # OK
flexible(3.14)   # TypeGuardError

Global Toggle

from philiprehberger_type_guard import enable, disable

disable()  # Turn off all guards (e.g., in production)
enable()   # Turn back on

Error Details

from philiprehberger_type_guard import TypeGuardError

try:
    greet(123, 3)
except TypeGuardError as e:
    print(e.param)     # "name"
    print(e.expected)  # "str"
    print(e.actual)    # <class 'int'>
    print(e.value)     # 123

API

  • @guard / @guard(enabled=True) — Decorator for runtime type checking
  • enable() / disable() — Global toggle
  • TypeGuardError — Raised on type mismatch (subclass of TypeError)

Development

pip install -e .
python -m pytest tests/ -v

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

philiprehberger_type_guard-0.1.4.tar.gz (4.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_type_guard-0.1.4-py3-none-any.whl (4.6 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_type_guard-0.1.4.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_type_guard-0.1.4.tar.gz
Algorithm Hash digest
SHA256 15d6c5a48060be7a298ac2722e5ddce3bddcbc6cad1baa05ce2b03cdcd81b559
MD5 ac16b56240d0061392a63e2f6e540e86
BLAKE2b-256 6e6c77f0f9db9a7c3ca13588ed36f96fdc1d915ffd0b5765ddad6992e3c504b7

See more details on using hashes here.

File details

Details for the file philiprehberger_type_guard-0.1.4-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_type_guard-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 b237c0838ae1987c8528f70878b36b5d26d35bb113e1675a7d3f1f1406a4e56a
MD5 ed87ef6d1035e898e8c017f063ffd57c
BLAKE2b-256 dca44c8035f4913b5d738e272826ddf1419561153ae1128f6042687ddc4f108f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page