Skip to content

Commit

Permalink
feat: support new 3.10 union
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Jan 23, 2021
1 parent 819641b commit c4736da
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ With this library, you can leverage `typing` types at runtime to do that!
# Check if `my_list` is a list of integers
isinstancex(my_list, [int]) # shortcut for typing.List[int]

# Check if `my_list` has only numbers (3.10 syntax)
isinstancex([3, 4, 3.14], list[int | float])

# Check if `my_list` starts with 2 integers and then has only strings
isinstancex(my_list, [int, int, str, ...]) # shortcut for Listx[int, int, str, ...] (see extra types)

Expand Down
6 changes: 6 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from collections import ChainMap, Counter

import pytest
Expand Down Expand Up @@ -202,6 +203,11 @@ def test_isinstancex_union(obj, tp, expected):
assert isinstancex(obj, tp) is expected


@pytest.mark.skipif(sys.version_info < (3, 10), reason="need python 3.10")
def test_isinstancex_union_310():
assert isinstancex([3, 4, 3.14], list[int | float])


@pytest.mark.parametrize(
"obj,tp,expected",
[
Expand Down
11 changes: 9 additions & 2 deletions typingx/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections.abc
import sys
from typing import Any, Callable, Dict, List, Set, Union, cast

from .types import Listx, Tuplex
Expand All @@ -21,6 +22,12 @@

TYPED_DICT_EXTRA_KEY = "__extra__"
NONE_TYPES = (None, NoneType, Literal[None])
if sys.version_info < (3, 10):
UNION_TYPES = (Union,)
else:
import types

UNION_TYPES = (Union, types.Union)


def _isinstancex(obj: Any, tp: TypeLike) -> bool:
Expand Down Expand Up @@ -52,8 +59,8 @@ def _isinstancex(obj: Any, tp: TypeLike) -> bool:
elif isinstance(tp, list):
return _isinstancex(obj, Listx[tuple(tp)])

# e.g. Union[str, int]
if origin is Union:
# e.g. Union[str, int] (or str|int in 3.10)
if origin in UNION_TYPES:
return isinstancex(obj, get_args(tp))

# e.g. Dict[str, int]
Expand Down

0 comments on commit c4736da

Please sign in to comment.