Register multiple excepthooks?

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Thu Aug 4 07:13:28 EDT 2022


On 2022-08-04 at 09:41:00 +0200,
Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:

>    Thank you both. I'll give this a try. I think it would be nice if
>    the standard library function atexit.register would be improved,
>    such that the registered functions would not only be called upon
>    (a) normal program termination, but that one could also register
>    functions that are called (b) upon error (c) unconditionally. Much
>    like (a) try - (b) except - (c) finally.

There.  You've just designed the top level of a better behaved, more
robust application (completely untested):

    on_normal_exit_funcs = list()
    on_error_exit_funcs = list()
    on_any_exit_funcs = list()

    def run_exit_funcs(exit_funcs):
        for func in exit_funcs:
            try: func()
            except e: maybe_do_some_logging(e)

    try:
        run_the_application()
        run_exit_funcs(on_normal_exit_funcs)
    except:
        run_exit_funcs(on_error_exit_funcs)
    finally:
        run_exit_funcs(on_any_exit_funcs)

    def register_normal_exit_func(f):
        on_normal_exit_funcs.append(f)

    def register_error_exit_func(f):
        on_error_exit_funcs.append(f)

    def register_any_exit_func(f):
        on_any_exit_funcs.append(f)

No, really.  There are worse ways to build an extremely generic, fairly
minimalist application framework.

Season to taste,¹ add it to your personal (or company) toolbox, and
refine and improve it as things come up.  You may discover some number
of common exit functions that are useful across appliations, too.

¹ are you object oriented, functional, imperative, or something else?
do you like long names, short names, names that follow some existing
coding standard, non-English names? do you have a standardized
logging/exception library?


More information about the Python-list mailing list