Skip to main content

Try not to stand out

Project description

logo

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

The @escape decorator suppresses exceptions in a wrapped function (including a coroutine one), which are passed in parentheses. In this way, you can pass any number of exceptions, for example:

import asyncio
import escape

@escape(ValueError, ZeroDivisionError)
def function():
    raise ValueError('oh!')

@escape(ValueError, ZeroDivisionError)
async def async_function():
    raise ZeroDivisionError('oh!')

function()  # Silence.
asyncio.run(async_function())  # Silence.

If you use @escape with parentheses but do not pass any exception types, no exceptions will be suppressed:

@escape()
def function():
    raise ValueError('oh!')

function()
# > ValueError: oh!

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(ValueError, default='some value')
def function():
    raise ValueError

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

Finally, you can use @escape as a decorator without parentheses.

@escape
def function():
    raise ValueError

function()  # Silence still.

In this mode, not all exceptions from the hierarchy are suppressed, but only those that can be expected in the user code. Exception and all its descendants are suppressed, as well as, starting with Python 3.11, groups of exceptions. However, exceptions GeneratorExit, KeyboardInterrupt and SystemExit are not escaped in this mode. 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.

You can also use the same set of exceptions in parenthesis mode as without parentheses. To do this, use the Ellipsis (three dots):

@escape(...)
def function_1():
    raise ValueError

@escape
def function_2():
    raise ValueError

function_1()  # These two functions are completely equivalent.
function_2()  # These two functions are completely equivalent.

Ellipsis can also be used in enumeration, along with other exceptions:

@escape(GeneratorExit, ...)

Context manager mode

You can use escape as a context manager, which escapes exceptions in the code block wrapped by it. You can call it according to the same rules as the decorator - pass exceptions or ellipsis there. It also works almost the same way as contextlib.suppress from the standard library, but with a bit more opportunities. Some examples:

with escape(ValueError):
    raise ValueError

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.SetDefaultReturnValueForContextManagerError: You cannot set a default value for the context manager. This is only possible for the decorator.

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.9.tar.gz (6.5 kB view details)

Uploaded Source

Built Distribution

exception_escaping-0.0.9-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file exception_escaping-0.0.9.tar.gz.

File metadata

  • Download URL: exception_escaping-0.0.9.tar.gz
  • Upload date:
  • Size: 6.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.8

File hashes

Hashes for exception_escaping-0.0.9.tar.gz
Algorithm Hash digest
SHA256 e62e2afc6eee5587382b5112d300746123e8b33320db13ed1419a4e68f149ca1
MD5 0b1aa03aece31d6763708f622e7bed32
BLAKE2b-256 3ed54b397b02e728bec9cdb5a6b1e63d794a05f5a3b9b05508d2dbf27bb0b0d2

See more details on using hashes here.

File details

Details for the file exception_escaping-0.0.9-py3-none-any.whl.

File metadata

File hashes

Hashes for exception_escaping-0.0.9-py3-none-any.whl
Algorithm Hash digest
SHA256 05c0644f046a89fcda64d894b2ff9bd3d1515703be254d15dd003cb73b9435d7
MD5 92d58c46c80fea77e5418a99a31a39c0
BLAKE2b-256 8b3c9eb29d7022e97da0e848d01f4b651e13b3a6c977732af69f6a356c4fd05f

See more details on using hashes here.

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