Skip to content

Context Manager

danling.utils.contextmanagers

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/contextmanagers.py
Python
@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