import signal
import time


# -------------------------
# PSR 2022/2023 - Typing Test
#
# Work done by:
#
# Jorge Silva
# --------------------------

# This code was inspired by https://stackoverflow.com/questions/8464391/what-should-i-do-if-socket-setdefaulttimeout

class Timeout:
    """Timeout class using ALARM signal."""

    class Timeout(Exception):
        pass

    def __init__(self, sec):
        self.sec = sec

    def __enter__(self):
        signal.signal(signal.SIGALRM, self.raise_timeout)
        signal.alarm(self.sec)

    def __exit__(self, *args):
        signal.alarm(0)  # disable alarm

    def raise_timeout(self, *args):
        raise Timeout.Timeout()