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

Avoid creating ref cycles #408

Merged
merged 10 commits into from
Jan 15, 2024
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
4 changes: 4 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Version history
This library adheres to
`Semantic Versioning 2.0 <https://semver.org/#semantic-versioning-200>`_.

**UNRELEASED**

- Avoid creating reference cycles when type checking unions

**4.1.5** (2023-09-11)

- Fixed ``Callable`` erroneously rejecting a callable that has the requested amount of
Expand Down
21 changes: 12 additions & 9 deletions src/typeguard/_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,16 +395,19 @@ def check_union(
memo: TypeCheckMemo,
) -> None:
errors: dict[str, TypeCheckError] = {}
for type_ in args:
try:
check_type_internal(value, type_, memo)
return
except TypeCheckError as exc:
errors[get_type_name(type_)] = exc
try:
for type_ in args:
try:
check_type_internal(value, type_, memo)
return
except TypeCheckError as exc:
errors[get_type_name(type_)] = exc

formatted_errors = indent(
"\n".join(f"{key}: {error}" for key, error in errors.items()), " "
)
formatted_errors = indent(
"\n".join(f"{key}: {error}" for key, error in errors.items()), " "
)
finally:
del errors # avoid creating ref cycle
raise TypeCheckError(f"did not match any element in the union:\n{formatted_errors}")


Expand Down
29 changes: 29 additions & 0 deletions tests/test_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,35 @@ def test_union_fail(self, annotation, value):
f" int: is not an instance of int"
)

@pytest.mark.skipif(
sys.implementation.name != "cpython",
reason="Test relies on CPython's reference counting behavior",
)
def test_union_reference_leak(self):
leaked = True

class Leak:
def __del__(self):
nonlocal leaked
leaked = False

def inner1():
leak = Leak() # noqa: F841
check_type(b"asdf", Union[str, bytes])

inner1()
assert not leaked

leaked = True

def inner2():
leak = Leak() # noqa: F841
with pytest.raises(TypeCheckError, match="any element in the union:"):
check_type(1, Union[str, bytes])

inner2()
assert not leaked


class TestTypevar:
def test_bound(self):
Expand Down