1
|
|
|
from typish._state import DEFAULT, State |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
def instance_of(obj: object, *args: object, state: State = DEFAULT) -> bool: |
5
|
|
|
""" |
6
|
|
|
Check whether ``obj`` is an instance of all types in ``args``, while also |
7
|
|
|
considering generics. |
8
|
|
|
|
9
|
|
|
If you want the instance check to be customized for your type, then make |
10
|
|
|
sure it has a __instancecheck__ defined (not in a base class). You will |
11
|
|
|
also need to register the get_type function by calling |
12
|
|
|
typish.register_get_type with that particular type and a handling callable. |
13
|
|
|
:param obj: the object in subject. |
14
|
|
|
:param args: the type(s) of which ``obj`` is an instance or not. |
15
|
|
|
:param state: any state that is used by typish. |
16
|
|
|
:return: ``True`` if ``obj`` is an instance of all types in ``args``. |
17
|
|
|
""" |
18
|
|
|
return all(_instance_of(obj, clsinfo, state) for clsinfo in args) |
19
|
|
|
|
20
|
|
|
|
21
|
|
View Code Duplication |
def _instance_of(obj: object, clsinfo: object, state: State = DEFAULT) -> bool: |
|
|
|
|
22
|
|
|
from typish.classes._literal import LiteralAlias, is_literal_type |
23
|
|
|
from typish.functions._subclass_of import subclass_of |
24
|
|
|
from typish.functions._get_type import get_type |
25
|
|
|
from typish.functions._is_from_typing import is_from_typing |
26
|
|
|
|
27
|
|
|
if not is_from_typing(clsinfo) and '__instancecheck__' in dir(clsinfo): |
28
|
|
|
return isinstance(obj, clsinfo) |
29
|
|
|
|
30
|
|
|
if is_literal_type(clsinfo): |
31
|
|
|
alias = LiteralAlias.from_literal(clsinfo) |
32
|
|
|
return isinstance(obj, alias) |
33
|
|
|
|
34
|
|
|
type_ = get_type(obj, use_union=True, state=state) |
35
|
|
|
return subclass_of(type_, clsinfo) |
36
|
|
|
|