Completed
Push — main ( b12314...8ccbcd )
by Yohann
17s queued 14s
created

pincer.utils.api_object   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 97
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 35
dl 0
loc 97
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A APIObject.from_dict() 0 9 1
A APIObject.to_dict() 0 5 1

1 Function

Rating   Name   Duplication   Size   Complexity  
B _asdict_ignore_none() 0 36 8
1
# -*- coding: utf-8 -*-
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# MIT License
3
#
4
# Copyright (c) 2021 Pincer
5
#
6
# Permission is hereby granted, free of charge, to any person obtaining
7
# a copy of this software and associated documentation files
8
# (the "Software"), to deal in the Software without restriction,
9
# including without limitation the rights to use, copy, modify, merge,
10
# publish, distribute, sublicense, and/or sell copies of the Software,
11
# and to permit persons to whom the Software is furnished to do so,
12
# subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
25
from __future__ import annotations
26
27
import copy
28
from dataclasses import dataclass, fields, _is_dataclass_instance
29
from typing import Dict, Union, Generic, TypeVar
30
31
from websockets.typing import Data
32
33
from pincer.utils.constants import MissingType
34
35
T = TypeVar("T")
1 ignored issue
show
Coding Style Naming introduced by
Class name "T" doesn't conform to PascalCase naming style ('[^\\W\\da-z][^\\W_]+$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
36
37
38
def _asdict_ignore_none(obj: Generic[T]) -> Union[tuple, dict, T]:
39
    """
40
    Returns a dict from a dataclass that ignores
41
    all values that are None
42
    Modification of _asdict_inner from dataclasses
43
44
    :param obj:
45
        Dataclass obj
46
    """
47
48
    if _is_dataclass_instance(obj):
0 ignored issues
show
unused-code introduced by
Unnecessary "elif" after "return"
Loading history...
49
        result = []
50
        for f in fields(obj):
1 ignored issue
show
Coding Style Naming introduced by
Variable name "f" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
51
            value = _asdict_ignore_none(getattr(obj, f.name))
52
53
            # This if statement was added to the function
54
            if not isinstance(value, MissingType):
55
                result.append((f.name, value))
56
57
        return dict(result)
58
59
    elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
60
        return type(obj)(*[_asdict_ignore_none(v) for v in obj])
61
62
    elif isinstance(obj, (list, tuple)):
63
        return type(obj)(_asdict_ignore_none(v) for v in obj)
64
65
    elif isinstance(obj, dict):
66
        return type(obj)(
67
            (
68
                _asdict_ignore_none(k),
69
                _asdict_ignore_none(v)
70
            ) for k, v in obj.items()
71
        )
72
    else:
73
        return copy.deepcopy(obj)
74
75
76
@dataclass
77
class APIObject:
78
    """
79
    Represents an object which has been fetched from the Discord API.
80
    """
81
82
    @classmethod
83
    def from_dict(cls: Generic[T], data: Data[str, Union[str, bool, int]]) -> T:
84
        """
85
        Parse an API object from a dictionary.
86
        """
87
        # Disable inspection for IDE because this is valid code for the
88
        # inherited classes:
89
        # noinspection PyArgumentList
90
        return cls(**data)
91
92
    def to_dict(self) -> Dict:
93
        """
94
        Transform the current object to a dictionary representation.
95
        """
96
        return _asdict_ignore_none(self)
97