Passed
Pull Request — main (#235)
by Yohann
01:42
created

pincer.utils.color   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 28
dl 0
loc 68
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Color.rbg() 0 9 1
A Color.hex() 0 9 1
B Color.__init__() 0 22 7
1
import string
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
from typing import Union
3
4
5
class Color:
6
    """
7
    A color in RGB.
8
9
    Parameters
10
    ---------
11
    c : Union[:class:`str`,:class:`int`]
12
        The hex color can be a string that optionally starts with an ``#`` or
13
        an int with the RGB values.
14
    Attributes
15
    ---------
16
    r : :class:`int`
17
        The red value for this color.
18
    g : :class:`int`
19
        The green value for this color.
20
    b : :class:`int`
21
        The blue value for this color.
22
    """
23
    _MIN_VALUE = 0
24
    _MAX_VALUE = 1 << 24
25
26
    def __init__(self, c: Union[str, int]) -> None:
27
        if isinstance(c, int):
28
            if c < self._MIN_VALUE or c >= self._MAX_VALUE:
29
                raise ValueError("The color must be between 0 and 16777215")
30
31
            self.r = c >> 16 & 255
32
            self.g = c >> 8 & 255
33
            self.b = c & 255
34
            return
35
36
        # Conversion modified from this answer
37
        # https://stackoverflow.com/a/29643643
38
        if c.startswith("#"):
39
            c = c[1:]
40
41
        if len(c) != 6:
42
            raise ValueError("Hex value must be 6 characters.")
43
44
        if any(digit not in string.hexdigits for digit in c):
45
            raise ValueError("Illegal hex digit character.")
46
47
        self.r, self.g, self.b = (int(c[n:n + 2], 16) for n in (0, 2, 4))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable n does not seem to be defined.
Loading history...
48
49
    @property
50
    def rbg(self):
51
        """
52
        Returns
53
        -------
54
        Tuple[:class:`int`, :class:`int` :class:`int`]
55
            Tuple value for rgb.
56
        """
57
        return self.r, self.g, self.b
58
59
    @property
60
    def hex(self):
61
        """
62
        Returns
63
        ---------
64
        str
65
            Str value for hex.
66
        """
67
        return f"{self.r:02x}{self.g:02x}{self.b:02x}"
68