Created
April 19, 2025 15:38
-
-
Save dboyliao/6142301a4dac8847098c4e603a49f249 to your computer and use it in GitHub Desktop.
Making Python callable type strict on its inputs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
from typing import Callable | |
from functools import wraps | |
def strict(func: Callable): | |
sig = inspect.signature(func) | |
params_to_check = {} | |
for name, param in sig.parameters.items(): | |
if param.annotation is not sig.empty: | |
params_to_check[name] = param.annotation | |
@wraps(func) | |
def wrapped(*args, **kwargs): | |
bind = sig.bind(*args, **kwargs) | |
for name in filter(lambda k: k in params_to_check, bind.arguments): | |
value = bind.arguments[name] | |
expect_type = params_to_check[name] | |
if not isinstance(value, expect_type): | |
raise ValueError(f"{name!r} should be of type {expect_type}, got {type(value)}") | |
return func(*args, **kwargs) | |
return wrapped | |
if __name__ == "__main__": | |
@strict | |
def add(x: int, y: int): | |
return x + y | |
print(add(1, 2)) # 3 | |
print(add(1, "2")) # ValueError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment