typish.functions._instance_of   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 41.67 %

Importance

Changes 0
Metric Value
eloc 16
dl 15
loc 36
rs 10
c 0
b 0
f 0
wmc 5

2 Functions

Rating   Name   Duplication   Size   Complexity  
A instance_of() 0 15 1
A _instance_of() 15 15 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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