Skip to content

Commit d0300bc

Browse files
committed
ensure_type: a method to cast a type and check the type at runtime
Signed-off-by: Gaëtan Lehmann <[email protected]>
1 parent 7753c59 commit d0300bc

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

lib/common.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import time
88
import traceback
99
from enum import Enum
10-
from typing import Dict, Literal, Optional, overload, TYPE_CHECKING, Union
10+
from typing import Any, Dict, Literal, Optional, Type, TypeVar, overload, TYPE_CHECKING, Union
1111
from uuid import UUID
1212

1313
import pytest
@@ -67,6 +67,14 @@ def expand_scope_relative_nodeid(scoped_nodeid, scope, ref_nodeid):
6767
logging.debug("scope: %r base: %r relative: %r", scope, base, scoped_nodeid)
6868
return "::".join(itertools.chain(base, (scoped_nodeid,)))
6969

70+
T = TypeVar("T")
71+
72+
def ensure_type(typ: Type[T], value: Any) -> T:
73+
"""Converts a value to the specified type. Also performs a runtime check."""
74+
if not isinstance(value, typ):
75+
raise TypeError(f"'{type(value).__name__}' object is not of the expected type '{typ.__name__}'")
76+
return value
77+
7078
def callable_marker(value, request):
7179
"""
7280
Process value optionally generated by fixture-dependent callable.

0 commit comments

Comments
 (0)