DEV Community

mtwtkman
mtwtkman

Posted on

GOTO sentence in Python

GOTO sentence is known as evil. I think so.

And Python has try ... except ... which works similar to GOTO sentence.

Suddenly I want to try to implement GOTO sentence like functionality in Python without using try ... except ....

Looks like below.

from functools import wraps
from contextlib import contextmanager


class AlreadyRegistered(Exception):
    ...


class UnknownLabel(Exception):
    ...


class GOTO:
    goto_funcs = {}
    current_label = None

    def __init__(self, name=None):
        self._name = name

    def jump(self, label: str):
        func = self.goto_funcs.get(label)
        if not func:
            raise UnknownLabel(label)
        self.current_label = label
        func()

    def __call__(self, label: str):
        def _inner(func):
            if label not in self.goto_funcs:
                self.goto_funcs[label] = func
            else:
                raise AlreadyRegistered(label)

            @wraps(func)
            def __inner(*args, **kwargs):
                return func(*args, **kwargs)
            return __inner
        return _inner

    def __str__(self):
        return f'{self.__class__}: {self._name}'


if __name__ == '__main__':
    goto = GOTO('mygoto')
    count = 0

    @goto('loop')
    def loop():
        global count
        print(f'current count = {count}')
        count += 1
        if count >= 2:
            return goto.jump('end')
        goto.jump('loop')


    @goto('end')
    def end():
        print('all done')


    loop()

This maybe very very limited and clearly very useless!

Bye.

Top comments (0)