Comments (7)
You can just write
def is_list_type(tp) -> bool:
return typing_inspect.get_origin(tp) is list
from typing_inspect.
@JelleZijlstra is that backwards compatible, even to Python 3.6?
I suspect one might better write
typing_inspect.get_origin(tp) in {list, List}
from typing_inspect.
Works in both python3.6 and python3.7
def is_list_type(tp) -> bool:
"""
Test if the type is a generic list type, including subclasses excluding
non-generic classes.
Examples::
is_list_type(int) == False
is_list_type(list) == False
is_list_type(List) == True
is_list_type(List[str, int]) == True
class MyClass(List[str]):
...
is_list_type(MyClass) == True
"""
return is_generic_type(tp) and issubclass(get_origin(tp) or tp, List)
And from tests:
params: List[Tuple[str, type, bool]] = \
[
("int", int, False),
("list", list, False),
("List", List, True),
("List[int]", List[int], True),
("ListChild", ListChild, True),
("List[ListChild]", List[ListChild], True),
("List[CustomJsonDataclass]", List[CustomJsonDataclass], True),
("CustomJsonDataclass", CustomJsonDataclass, False),
("GenericListChild", GenericListChild, True),
("GenericListChild[int, bool]", GenericListChild[int, bool], True),
]
for name, tp, expected in params:
with self.subTest(name, expected=expected):
self.assertEqual(expected, is_list_type(tp))
from typing_inspect.
See also typing.get_origin
, typing.get_args
added in Python 3.8.
from typing_inspect.
Fwiw, I arrived here looking for something like is_sequence_type
, to return True for all of list, tuple, set, etc
The above solutions did not work for me given that I dont know the incoming annotation, which are not always issubclass
-able. It's also perhaps not obvious to me why one would want to exclude list
in the most recent is_generic_type(tp) and issubclass(get_origin(tp) or tp, List)
solution.
is_generic_type(tp) and issubclass(get_origin(tp) or tp, List)
returns False for list
, and issubclass
raises TypeError
for various typing types like Literal["s"]
.
I ended up with (although i may be misinformed and this fails in ways I dont yet understand):
def is_subclass(typ, superclass):
if not isinstance(typ, type):
return False
return issubclass(typ, superclass)
def is_sequence_type(typ):
return is_subclass(get_origin(typ) or typ, SUPPORTED_SEQUENCE_TYPES)
SUPPORTED_SEQUENCE_TYPES = (typing.List, typing.Tuple, typing.Set)
In my humble, uneducated opinion it'd be ideal if this library were able to include runtime equivalents for these sorts of things that have corresponding values-apis in stdlib, even if (as the comments towards the top imply) it's "easy" to compose them from other apis already exposed from this library.
from typing_inspect.
What is sequence in your definition? Is it any iterable, or collection of finite size? One thing you can do is to check if the class matches the protocol via magic Merida methods — __iter__
for iterables and __len__
(iirc) for collections
from typing_inspect.
For my purposes, i'm talking about equivalency to Sequence, although now that i'm looking at it, i was is_sequence_type(tp) and not is_mapping_type(tp)
. I probably should be using the literal magic method interface rather than explicitly calling out the types as i am.
But I wouldn't be surprised if there were some weird false positives in the context of the type system, given that any generic type is going implement __getitem__
(?).
mostly posted to suggest that i think there's value in a library like this one implementing these "easily" derivable runtime checks for common use, which the earlier comments seemed to be advocating against.
from typing_inspect.
Related Issues (20)
- is_literal broken with new typing_extensions HOT 3
- get_origin gives inconsistent results for differently defined Unions HOT 3
- `get_parameters` returns empty tuples for all collection types in python 3.10.13
- Add Final type
- get_origin(Dict) returns None in python 3.9 HOT 1
- Support Python 3.9 HOT 4
- Add a simple is_type(t) method HOT 2
- 0.6.0: test suite is failing HOT 3
- Python 3.9 support breaks List HOT 2
- ImportError on typing_extensions HOT 1
- Fix for Python 3.9.0/1 does not work with typing_extensions 3.7.4. HOT 1
- `typing_inspect.get_args` `Annotated` metadata args HOT 1
- test_typed_dict_typing_extension fails with typing_extensions==4.1.1 HOT 3
- New release? HOT 2
- `get_origin()` doesn't support PEP 585 generic types? HOT 2
- Breaks `marshmallow_dataclass.NewType` HOT 4
- `get_parameters` throws exception with non-indexed types from `typing` on python 3.10 HOT 1
- `typed_dict_keys` fails to return data on 3.10 HOT 1
- BUG: is_union_type return None sometime HOT 2
- `get_parameters` failed for Tuple HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from typing_inspect.