Skip to content

Context Managers

danling.utils.context_managers

debug

Python
debug(enable: bool = True, error: Exceptions = Exception, exclude: Optional[Exceptions] = None)

Contextmanager to enter debug mode on error except for exclude.

debug is intended to be used to catch the error and enter debug mode. Since it is mainly for development purposed, we include an enable args so that it can be deactivated.

Parameters:

Name Type Description Default

enable

bool

Whether to enable the contextmanager. Defaults to True.

True

error

Exceptions

The error to catch. Defaults to Exception.

Exception

exclude

Optional[Exceptions]

The error to exclude. Defaults to None.

None
Source code in danling/utils/context_managers.py
Python
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@contextmanager
def debug(
    enable: bool = True,
    error: Exceptions = Exception,
    exclude: Optional[Exceptions] = None,
):
    """
    Contextmanager to enter debug mode on `error` except for `exclude`.

    `debug` is intended to be used to catch the error and enter debug mode.
    Since it is mainly for development purposed, we include an `enable` args so that it can be deactivated.

    Args:
        enable: Whether to enable the contextmanager.
            Defaults to `True`.
        error: The error to catch.
            Defaults to `Exception`.
        exclude: The error to exclude.
            Defaults to `None`.
    """

    if not enable:
        yield
        return
    try:
        yield
    except error as exc:  # pylint: disable=broad-exception-caught
        if exclude is not None and isinstance(exc, exclude):
            raise exc
        _, m, tb = sys.exc_info()
        print(repr(m), file=sys.stderr)
        pdb.post_mortem(tb)
    finally:
        pass