<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def timed(timeout, fn, args=(), kargs={}):
 """For a nonzero timeout, evaluates a call expression in a separate thread. If the timeout is 0, the expression is evaluated in the main thread. PARAMETERS: fn -- function; Python function to be evaluated args -- tuple; positional arguments for fn kargs -- dict; keyword arguments for fn timeout -- int; number of seconds before timer interrupt RETURN: Result of calling fn(*args, **kargs). RAISES: Timeout -- if thread takes longer than timeout to execute Error -- if calling fn raises an error, raise it """

    if timeout == 0:
        return fn(*args, **kargs)

    submission = __ReturningThread(fn, args, kargs)
    submission.start()
    submission.join(timeout)
    if submission.is_alive():
        raise exceptions.Timeout(timeout)
    if submission.error is not None:
        raise submission.error
    return submission.result