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

fix: fix safe_issubclass for NewType #678

Merged
merged 6 commits into from
Nov 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ ignore = [

[tool.ruff.lint.per-file-ignores]
"tests/*.py" = ["D", "S", "E501"]
"tests/test_util.py" = ["D", "S", "E501", "UP006"]
"docs/*.py" = ["B"]
"docs/examples/*.py" = ["D", "B", "E501"]
"src/magicgui/widgets/_image/*.py" = ["D"]
Expand Down
2 changes: 2 additions & 0 deletions src/magicgui/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ def _safe_isinstance_tuple(obj: object, superclass: object) -> bool:

def safe_issubclass(obj: object, superclass: object) -> bool:
"""Safely check if obj is a subclass of superclass."""
if obj == superclass:
Czaki marked this conversation as resolved.
Show resolved Hide resolved
return True
if isinstance(superclass, tuple):
return any(safe_issubclass(obj, s) for s in superclass)
obj_origin = get_origin(obj)
Expand Down
9 changes: 9 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,12 @@ def test_subclass_future(self):
assert safe_issubclass(Future[list[int]], Future[list])
assert safe_issubclass(Future[list[int]], Future[list[int]])
assert not safe_issubclass(Future[list[int]], Future[list[str]])

def test_subclass_new_type(self):
new_int = typing.NewType("new_int", int)

assert safe_issubclass(new_int, new_int)
assert safe_issubclass(list[new_int], typing.List[new_int])
assert safe_issubclass(typing.List[new_int], list[new_int])
assert safe_issubclass(list[new_int], typing.Sequence[new_int])
assert safe_issubclass(list[new_int], list[new_int])
tlambert03 marked this conversation as resolved.
Show resolved Hide resolved