Skip to content

Commit 1efb579

Browse files
committed
ensure_type: supports complex types
like TypeDict Signed-off-by: Gaëtan Lehmann <[email protected]>
1 parent 9bc0870 commit 1efb579

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/common.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from contextlib import suppress
12
import getpass
23
import inspect
34
import itertools
@@ -7,6 +8,7 @@
78
import time
89
import traceback
910
from enum import Enum
11+
from pydantic import TypeAdapter, ValidationError
1012
from typing import Any, Dict, Literal, Optional, Type, TypeVar, overload, TYPE_CHECKING, Union
1113
from uuid import UUID
1214

@@ -71,8 +73,21 @@ def callable_marker(value, request):
7173
T = TypeVar("T")
7274

7375
def ensure_type(typ: Type[T], value: Any) -> T:
74-
"""Converts a value to the specified type. Also performs a runtime check."""
75-
if not isinstance(value, typ):
76+
"""
77+
Converts a value to the specified type.
78+
79+
Unlike typing.cast, it also performs a runtime check.
80+
Unlike isinstance, it also supports complex types.
81+
"""
82+
ok = False
83+
try:
84+
ok = isinstance(value, typ)
85+
except TypeError:
86+
# not just a simple type, lets try with pydantic
87+
with suppress(ValidationError):
88+
TypeAdapter(typ).validate_python(value)
89+
ok = True
90+
if not ok:
7691
raise TypeError(f"'{type(value).__name__}' object is not of the expected type '{typ.__name__}'")
7792
return value
7893

requirements/base.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ pluggy>=1.1.0
66
requests
77
legacycrypt
88
pytest-dependency
9+
pydantic

0 commit comments

Comments
 (0)