I think you can already do all of this with a custom exception-swallowing
decorator function.

Something like this:

from functools import wraps

def swallow(*exceptions, default=Exception, result=None):
    if not exceptions:
        exceptions = Exception,
    def decorator(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except exceptions:
                return result
        return wrapped
    return decorator

Then just write:

@swallower()
def some_func():
    log_to_telegram('This is a not important message. It's okay even if it
isn\'t delivered.')

For divide by zero errors you need to put the division operation in a
lambda function:

safe_divide = swallow(DivideByZero, result=0)
division = safe_divide(lambda: a/b)

I didn't test any of this but it should be working.

On Sun, May 23, 2021, 8:54 AM Shivam Saini <shivams...@gmail.com> wrote:

> Sometimes, we need to execute a statement, which might throw an exception
> and we want to return None if it causes an exception. In short, we want to
> run that command as failsafe mode, so that it doesn't cause abnormal
> termination in case of any exception.
>
> *Approach till now:*
>
> def log_to_telegram(text):
>     ''' Suppose you want to send some log to some telegram channel using
> telegram bot api. It might raise Network Error, or Invalid Bot token error.
>     '''
>     send_message(CHANNEL, BOT_TOKEN, TEXT) # Suppose send_message is a
> function wrapper for telegram bot api.
>
> def some_func():
>     try:
>         log_to_telegram('This is a not important message. It's okay even
> if it isn\'t delivered.')
>     except:
>         pass
>     # Next work
>
> *Suggested approach:*
>
> # consider the same log_to_telegram function as defined in previous example
>
> def some_func():
>     safe log_to_telegram('This is a not important message. It's okay even
> if it isn\'t delivered.')
>     # safe keyword ensures that it raises no exception and the process
> isn't terminated even if log_to_telegram function raises an exception.
>
> *Other examples:*
>
> *1. By default, it will return None.*
> *    Example: *
>         try:
>            file = open('some_file')
>        except:
>            file = None
> *    Can be rewritten as:*
>        file = safe open('some_file')
>
> *2. We can provide a return value explicitly which should be returned in
> case of some exception.*
> *    Example: *
>         try:
>            division = a/b
>        except:
>            division = 0
> *    Can be rewritten as:*
>         division   = safe(0) a/b
>
> *3. We can set what exceptions we want to be 'safed'.*
> *    Example: *
>         try:
>            element = some_list[index]/divisor
>        except ZeroDivisionError:
>            element = 0  # It will make element zero if divisor is zero,
> but it will not except IndexError in case index is out of range for
> some_list
> *    Can be rewritten as:*
>        element = safe(0, ZeroDivisionError) some_list[index]/divisor
>
> *I think this keyword should be there in python, it will make code short
> and readable. *
> _______________________________________________
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/5SEDN6AUM7LZPZZJJZ3RMAKHKHN6N665/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ORKXAAH2EZFYHJMVU74H5R6BSJVMMER7/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to