Last active
May 12, 2025 15:18
-
-
Save stuaxo/dbed29d09aa725abd8334ff81d89c1eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_container_type(type_hint: Any) -> bool: | |
"""\ | |
:return: for containers you might add to a dataclass, like List[...] but types like str. | |
""" | |
origin = get_origin(type_hint) or type_hint | |
if origin is str: | |
return False | |
if isinstance(origin, type): | |
return issubclass(origin, collections.abc.Container) | |
return False | |
# Test | |
from typing import List, Dict, Set, Tuple, Union, Optional | |
# Standard containers | |
assert is_container_type(list) is True | |
assert is_container_type(dict) is True | |
assert is_container_type(set) is True | |
# Generic versions | |
assert is_container_type(List[int]) is True | |
assert is_container_type(Dict[str, int]) is True | |
assert is_container_type(Set[float]) is True | |
assert is_container_type(Tuple[int, str]) is True | |
# Non-containers | |
assert is_container_type(int) is False | |
# Container-like objects (and strings... which only contain characters so are not wanted here) | |
assert is_container_type(str) is False | |
assert is_container_type(Union[int, str]) is False | |
assert is_container_type(Optional[int]) is False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment