ГОТО
Приговор известен как зло. Я так думаю.
И Python имеет попробуй ... кроме ...
который работает похоже на ГОТО
приговор.
Внезапно я хочу попытаться осуществить ГОТО
предложение, как функциональность в Python без использования попробуй ... кроме ...
Отказ
Выглядит как ниже.
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()
Это может быть очень очень ограниченным и явно очень бесполезным!
До свидания.
Оригинал: “https://dev.to/mtwtkman/goto-sentence-in-python-282j”