Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 514a040

Browse files
committed
add-annotation-tests
1 parent e747e0d commit 514a040

2 files changed

Lines changed: 47 additions & 6 deletions

File tree

IPython/core/guarded_eval.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -573,16 +573,19 @@ def _is_type_annotation(obj) -> bool:
573573
"""
574574
if isinstance(obj, type):
575575
return True
576-
if hasattr(typing, "get_origin"):
577-
if typing.get_origin(obj) is not None:
578-
return True
579-
if hasattr(obj, "__module__") and obj.__module__ == "typing":
580-
return True
581576
if isinstance(obj, types.GenericAlias):
582577
return True
583578
if hasattr(types, "UnionType") and isinstance(obj, types.UnionType):
584579
return True
585-
if type(obj).__name__ in ("_GenericAlias", "_SpecialForm", "_UnionGenericAlias"):
580+
if isinstance(obj, (typing._SpecialForm, typing._BaseGenericAlias)):
581+
return True
582+
if isinstance(obj, typing.TypeVar):
583+
return True
584+
# Types that support __class_getitem__
585+
if isinstance(obj, type) and hasattr(obj, "__class_getitem__"):
586+
return True
587+
# Fallback: check if get_origin returns something
588+
if hasattr(typing, "get_origin") and get_origin(obj) is not None:
586589
return True
587590

588591
return False

tests/test_guarded_eval.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@
1212
TypeGuard,
1313
Union,
1414
TypedDict,
15+
TypeVar,
16+
List,
17+
Callable,
18+
Any,
19+
Dict,
1520
)
1621
from functools import partial
1722
from IPython.core.guarded_eval import (
@@ -22,6 +27,7 @@
2227
)
2328
from IPython.testing import decorators as dec
2429
import pytest
30+
from IPython.core.guarded_eval import _is_type_annotation
2531

2632

2733
from typing import Self, LiteralString
@@ -579,6 +585,38 @@ def test_mock_class_and_func_instances(code, expected):
579585
assert isinstance(value, expected)
580586

581587

588+
@pytest.mark.parametrize(
589+
"annotation,expected",
590+
[
591+
# Basic types
592+
(int, True),
593+
(str, True),
594+
(list, True),
595+
# Typing generics
596+
(list[str], True),
597+
(dict[str, int], True),
598+
(Optional[int], True),
599+
(Union[int, str], True),
600+
# Special forms
601+
(AnyStr, True),
602+
(TypeVar("T"), True),
603+
(Callable[[int], str], True),
604+
(Literal["GET", "POST"], True),
605+
(Any, True),
606+
(str | int, True),
607+
# Nested
608+
(List[Dict[str, int]], True),
609+
# Non-annotations
610+
(42, False),
611+
("string", False),
612+
([1, 2, 3], False),
613+
(None, False),
614+
],
615+
)
616+
def test_is_type_annotation(annotation, expected):
617+
assert _is_type_annotation(annotation) == expected
618+
619+
582620
@pytest.mark.parametrize(
583621
"code,expected",
584622
[

0 commit comments

Comments
 (0)