[Python] is this goto.py constructed correctly:

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I've devised a method to mimic the goto statement in Python, which is traditionally not available in the language. This approach uses a custom exception to simulate jumping between labeled functions. The code works well for simple jumps and I'd appreciate any feedback on potential pitfalls or improvements.

    Here’s the Python code implementing the goto functionality:

    class Goto(Exception):
    pass

    def goto(label, globals_=globals()):
    if label in globals_:
    func = globals_[label]
    func()
    else:
    raise ValueError("Label %s not defined" % label)

    def label(func):
    def wrapper(*args, **kwargs):
    try:
    return func(*args, **kwargs)
    except Goto as jump:
    if jump.args[0] == func.__name__:
    return wrapper(*args, **kwargs)
    else:
    raise
    return wrapper

    @label
    def start():
    print("This is the start.")
    goto("end")

    @label
    def middle():
    print("This is the middle.")

    @label
    def end():
    print("This is the end.")

    start()


    What you should see in your output:

    This is the start.
    This is the end.

    Continue reading...

Compartilhe esta Página