Passed
Push — main ( 60119b...e5c7f7 )
by Douglas
02:02
created

pocketutils.misc.warning_utils   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 87
rs 10
c 0
b 0
f 0
wmc 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A WarningsConfig.never() 0 6 2
A WarningsConfig.filter_common() 0 8 1
A WarningsConfig.simplify_format() 0 13 1
A WarningsConfig.once() 0 6 2
A WarningsConfig.filter() 0 5 1
A WarningsConfig.common_never() 0 8 1
A WarningsConfig.common_once() 0 4 1
A WarningsConfig.__init__() 0 2 1
1
from __future__ import annotations
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
3
import warnings
4
from pathlib import Path
5
from typing import AbstractSet
6
7
from pocketutils.core.exceptions import NotConstructableError
8
9
10
class WarningsConfig:
11
    """
12
    Convenient API to add warning filters.
13
    Also provides :meth:`simplify_format`, which sets a less-verbose warning formatter.
14
15
    Example:
16
        >>> (
17
                GlobalWarningUtils.simplify_format()
18
                .filter_common()
19
                .never("Number of features differ")
20
            )
21
    """
22
23
    def __init__(self):
24
        raise NotConstructableError(f"Do not instantiate {self.__class__.__name__}")
25
26
    @classmethod
27
    def simplify_format(cls) -> __qualname__:
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable '__qualname__'
Loading history...
28
        """
29
        Common initialization, including setting a better formatter that doesn't say "WARNING:py.warnings:".
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (108/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
30
        """
31
32
        def new_formatter(message, category, filename, lineno, line=None):
0 ignored issues
show
Unused Code introduced by
The argument line seems to be unused.
Loading history...
33
            cat = category.__name__.replace("Warning", "")
34
            s = f"{Path(filename).name}:{lineno}: {cat}: {message}"
0 ignored issues
show
Coding Style Naming introduced by
Variable name "s" 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...
35
            return s.replace("WARNING:py.warnings:", "")
36
37
        warnings.formatwarning = new_formatter
38
        return cls
39
40
    @classmethod
41
    def filter(cls, **kwargs) -> __qualname__:
42
        """Same as warnings.filterwarnings."""
43
        warnings.filterwarnings(**kwargs)
44
        return cls
45
46
    @classmethod
47
    def never(cls, *substrings: str) -> __qualname__:
48
        """Adds a filter containing this substring, never showing the warning."""
49
        for substring in substrings:
50
            warnings.filterwarnings(message=".*?" + substring + ".*", action="ignore")
51
        return cls
52
53
    @classmethod
54
    def once(cls, *substrings: str) -> __qualname__:
55
        """Adds a filter containing this substring, warning only once."""
56
        for substring in substrings:
57
            warnings.filterwarnings(message=".*?" + substring + ".*", action="once")
58
        return cls
59
60
    @classmethod
61
    def filter_common(cls) -> __qualname__:
62
        """
63
        Adds filters for common unavoidable warnings from numpy, pandas, scikit-learn, etc.
64
65
        See ``common_never_substrings`` and ``common_once_substrings``.
66
        """
67
        return cls.never(*cls.common_never()).once(*cls.common_once())
68
69
    @classmethod
70
    def common_never(cls) -> AbstractSet[str]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
71
        return {
72
            "libuv only supports millisecond timer resolution",
73
            "or '1type' as a synonym of type is deprecated",
74
            "Series.nonzero() is deprecated and will be removed in a future version",
75
            "Monkey-patching ssl after ssl has already been imported may lead to errors",
76
            "your performance may suffer as PyTables will pickle object types that it cannot map directly to c-types",
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (118/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
77
        }
78
79
    @classmethod
80
    def common_once(cls) -> AbstractSet[str]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
81
        return {
82
            "Trying to unpickle estimator",
83
        }
84
85
86
__all__ = ["WarningsConfig"]
87