Source code for crappy.links.link

# coding: utf-8

# Link class. All connection between Blocks should be made with this.


from multiprocessing import Pipe
from time import time
from threading import Thread
from copy import copy
from functools import wraps
from typing import Callable, Union, Any

from .._global import CrappyStop


[docs]def error_if_string(recv: Callable) -> Callable: """Decorator to raise an error if the function returns a string.""" @wraps(recv) def wrapper(*args, **kwargs): ret = recv(*args, **kwargs) if isinstance(ret, str): raise CrappyStop return ret return wrapper
[docs]class MethodThread(Thread): """ThreadMethodThread, daemonic descendant class of :mod:`threading`. Thread which simply runs the specified target method with the specified arguments. """ def __init__(self, target: Callable, args, kwargs) -> None: Thread.__init__(self) self.setDaemon(True) self.target, self.args, self.kwargs = target, args, kwargs self.start()
[docs] def run(self) -> None: try: self.result = self.target(*self.args, **self.kwargs) except Exception as e: self.exception = e else: self.exception = None
[docs]def win_timeout(timeout: float = None) -> Callable: """Decorator for adding a timeout to a link send.""" def win_timeout_proxy(f: Callable) -> Callable: @wraps(f) def wrapper(*args, **kwargs) -> Any: worker = MethodThread(f, args, kwargs) if timeout is None: return worker worker.join(timeout) if worker.is_alive(): raise TimeoutError("timeout error in pipe send") elif worker.exception is not None: raise worker.exception else: return worker.result return wrapper return win_timeout_proxy