Skip to main content

Try not to stand out

Project description

exception_escaping

Downloads Downloads codecov Lines of code Hits-of-Code Test-Package Python versions PyPI version Checked with mypy Ruff

If you've just confessed and you can't wait to sin again, try this package. It will help you hide your mistakes and make your life more carefree.

Table of contents

Quick start

Install it:

pip install exception_escaping

And use:

import escape

@escape
def function():
    raise ValueError

function()  # The exception is suppressed.

Read about other library features below.

Decorator mode

You can hang the escape decorator on any function, including a coroutine one. Exceptions that occur internally will be suppressed.

An example with a regular function:

@escape
def function():
    raise ValueError

And with coroutine one:

@escape
async def coroutine_function():
    raise ValueError

The decorator will work both with and without brackets:

@escape()  # This will work too.
def function():
    ...

If an exception occurred inside the function wrapped by the decorator, it will return the default value - None. You can specify your own default value:

@escape(default='some value')
def function():
    raise ValueError

assert function() == 'some value'  # It's going to work.

Context manager mode

You can use escape as a context manager. It works almost the same way as contextlib.suppress from the standard library. However, in this case, you can choose whether to use the context manager with or without brackets:

# Both options work the same way.

with escape:
    raise ValueError

with escape():
    raise ValueError

However, as you should understand, the default value cannot be specified in this case. If you try to specify a default value for the context manager, get ready to face an exception:

with escape(default='some value'):
    ...

# escape.errors.SetDefaultReturnValueForDecoratorError: You cannot set a default value for the context manager. This is only possible for the decorator.

Which exceptions are escaped?

By default, not all exceptions from the hierarchy are escaped. This only applies to Exception and all its descendants. Starting with Python 3.11, groups of exceptions appear - and they are also escaped by default. However, exceptions GeneratorExit, KeyboardInterrupt and SystemExit are not escaped by default. This is due to the fact that in most programs none of them is part of the semantics of the program, but is used exclusively for system needs. For example, if KeyboardInterrupt was blocked, you would not be able to stop your program using the Control-C keyboard shortcut.

If you want to expand or narrow the range of escaped exceptions, use the exceptions argument. You must pass a list or tuple of exception types.

It works for the decorator mode:

@escape(exceptions=[ValueError]):
def function():
    raise ValueError  # It will be suppressed.

@escape(exceptions=[ValueError]):
def function():
    raise KeyError  # And this is not.

... and for the context manager mode:

with escape(exceptions=[ValueError]):
    raise ValueError  # It will be suppressed.

with escape(exceptions=[ValueError]):
    raise KeyError  # And this is not.

Logging

You can pass a logger object to the escape. In such case, if an exception is raised inside the context or the function wrapped by the decorator, it will be logged:

import logging
import escape

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.StreamHandler(),
    ]
)

logger = logging.getLogger('logger_name')

with escape(logger=logger):
    1/0

# You will see a description of the error in the console.

It works in any mode: both in the case of the context manager and the decorator.

Only exceptions are logged. If the code block or function was executed without errors, the log will not be recorded. Also the log is recorded regardless of whether the exception was suppressed or not. However, depending on this, you will see different log messages to distinguish one situation from another.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

exception_escaping-0.0.8.tar.gz (7.5 kB view hashes)

Uploaded Source

Built Distribution

exception_escaping-0.0.8-py3-none-any.whl (6.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page