Olarn's DevBlog
Escaping from nested functions using exception
Sorry, failed to load main article image
Bantukul Olarn
    
Jun 15 2018 12:23
  

Escaping from nested functions using exception.

Exception raising behavior can be used to jump out of nested function in one go in python.

Although not well advertised in the documentation, the Exception class actually accepts generic PyObject as it's argument, so it can be used to return arbitrary data.

from __future__ import (
    print_function,
    absolute_import,
    division,
)


class GetMeOut(Exception):
    pass


def afn():
    def afn1():
        def afn2():
            def afn3():
                def afn4():
                    data = (1, 2, 3, 4, 5)
                    raise GetMeOut(data)

                afn4()

            afn3()

        afn2()

    afn1()


try:
    afn()
except GetMeOut as gm:
    # exception.message does not exists on python3
    print(gm.args)
    print(type(gm.args))

Tags: