Skip to content
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

Added cv_type_checking context var #25

Merged
merged 3 commits into from
Apr 17, 2023
Merged
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
8 changes: 8 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,18 @@ packages = [{ include = "runtype" }]
[tool.poetry.dependencies]
python = "^3.6"
dataclasses = {version = "*", python = "~3.6"}
contextvars = {version = "*", python = "~3.6"}

[tool.poetry.dev-dependencies]
typing_extensions = "*"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.pytest.ini_options]
minversion = "6.0"
# addopts = "-ra -q"
testpaths = [
"tests",
]
2 changes: 1 addition & 1 deletion runtype/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .dataclass import dataclass
from .dispatch import DispatchError, MultiDispatch
from .validation import PythonTyping, TypeSystem, TypeMismatchError, assert_isa, isa, issubclass, validate_func, is_subtype
from .validation import PythonTyping, TypeSystem, TypeMismatchError, assert_isa, isa, issubclass, validate_func, is_subtype, cv_type_checking
from .pytypes import Constraint, String, Int

__version__ = "0.3.1"
Expand Down
18 changes: 18 additions & 0 deletions runtype/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import inspect
import sys
import contextvars
from contextlib import contextmanager

if sys.version_info < (3, 7):
# python 3.6
Expand Down Expand Up @@ -30,3 +32,19 @@ def get_func_signatures(typesystem, f):

typesigs.append(typesig)
return typesigs


class ContextVar:
def __init__(self, default, name=''):
self._var = contextvars.ContextVar(name, default=default)

def get(self):
return self._var.get()

@contextmanager
def __call__(self, value):
token = self._var.set(value)
try:
yield
finally:
self._var.reset(token)
11 changes: 8 additions & 3 deletions runtype/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,21 @@
from functools import wraps

from .common import CHECK_TYPES
from .utils import get_func_signatures
from .utils import get_func_signatures, ContextVar
from .pytypes import TypeMismatchError, type_caster
from .typesystem import TypeSystem

# cv_type_checking allows the user to define different behaviors for their objects
# while they are being type-checked.
# This is especially useful if they overrode __hash__ or __eq__ in nonconventional ways.
cv_type_checking: ContextVar = ContextVar(False, name='type_checking')

def ensure_isa(obj, t, sampler=None):
"""Ensure 'obj' is of type 't'. Otherwise, throws a TypeError
"""
t = type_caster.to_canon(t)
t.validate_instance(obj, sampler)
with cv_type_checking(True):
t = type_caster.to_canon(t)
t.validate_instance(obj, sampler)


def is_subtype(t1, t2):
Expand Down
19 changes: 18 additions & 1 deletion tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import logging
logging.basicConfig(level=logging.INFO)

from runtype import Dispatch, DispatchError, dataclass, isa, is_subtype, issubclass, assert_isa, String, Int, validate_func
from runtype import Dispatch, DispatchError, dataclass, isa, is_subtype, issubclass, assert_isa, String, Int, validate_func, cv_type_checking
from runtype.dataclass import Configuration

try:
Expand Down Expand Up @@ -167,6 +167,23 @@ def test_literal_comparison(self):
# and our caching swaps between them.
assert is_subtype(typing.Literal[True], bool)

@unittest.skipIf(not hasattr(typing, 'Literal'), "Literals not supported in this Python version")
def test_context_vars(self):
class BadEq:
def __init__(self, smart):
self.smart = smart

def __eq__(self, other):
if self.smart and cv_type_checking.get():
return False
raise NotImplementedError()

inst = BadEq(False)
self.assertRaises(NotImplementedError, isa, inst, typing.Literal[1])

inst = BadEq(True)
assert isa(inst, typing.Literal[1]) == False


class TestDispatch(TestCase):
def setUp(self):
Expand Down
24 changes: 12 additions & 12 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,21 +109,21 @@ def test_constraint(self):


def test_typesystem(self):
t = TypeSystem()
o = object()
assert t.canonize_type(o) is o
t = TypeSystem()
o = object()
assert t.canonize_type(o) is o

class IntOrder(TypeSystem):
def issubclass(self, a, b):
return a <= b
class IntOrder(TypeSystem):
def issubclass(self, a, b):
return a <= b

def get_type(self, a):
return a
def get_type(self, a):
return a

i = IntOrder()
assert i.isinstance(3, 3)
assert i.isinstance(3, 4)
assert not i.isinstance(4, 3)
i = IntOrder()
assert i.isinstance(3, 3)
assert i.isinstance(3, 4)
assert not i.isinstance(4, 3)

def test_pytypes(self):
assert Tuple <= Tuple
Expand Down