Skip to content

Runtime type checking POC #1554

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cognite/client/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ class CogniteException(Exception):
pass


class CogniteTypeError(CogniteException): ...


class CogniteProjectAccessError(CogniteException):
"""Raised when we get a 401 response from the API which means we don't have project access at all."""

Expand Down
37 changes: 37 additions & 0 deletions cognite/client/utils/_runtime_type_checking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import sys
from collections.abc import Callable
from inspect import isfunction
from typing import Any, TypeVar, cast

from beartype import beartype
from beartype.roar import BeartypeCallHintParamViolation

from cognite.client.exceptions import CogniteTypeError

T_Callable = TypeVar("T_Callable", bound=Callable)
T_Class = TypeVar("T_Class", bound=type)


class Settings:
enable_runtime_type_checking: bool = False


def runtime_type_checked_method(f: T_Callable) -> T_Callable:
if (sys.version_info < (3, 10)) or not Settings.enable_runtime_type_checking:
return f
beartyped_f = beartype(f)

def f_wrapped(*args: Any, **kwargs: Any) -> Any:
try:
return beartyped_f(*args, **kwargs)
except BeartypeCallHintParamViolation as e:
raise CogniteTypeError(e.args[0])

return cast(T_Callable, f_wrapped)


def runtime_type_checked(c: T_Class) -> T_Class:
for name in dir(c):
if not name.startswith("_") or (name == "__init__" and isfunction(getattr(c, name))):
setattr(c, name, runtime_type_checked_method(getattr(c, name)))
return c
Loading
Loading