Advertisement
Fhernd

funciones_callback_en_linea.py

Nov 18th, 2018
2,879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. from queue import Queue
  2. from functools import wraps
  3.  
  4. def aplicar_asincronismo(funcion, args, *, callback):
  5.     resultado = funcion(*args)
  6.  
  7.     callback(resultado)
  8.  
  9. class Asincronica:
  10.     def __init__(self, funcion, args):
  11.         self.funcion = funcion
  12.         self.args = args
  13.  
  14. def asincronismo(funcion):
  15.     @wraps(funcion)
  16.     def envoltura(*args):
  17.         f = funcion(*args)
  18.         cola = Queue()
  19.         cola.put(None)
  20.  
  21.         while True:
  22.             resultado = cola.get()
  23.  
  24.             try:
  25.                 a = f.send(resultado)
  26.                 aplicar_asincronismo(a.funcion, a.args, callback=cola.put)
  27.             except StopIteration:
  28.                 break
  29.  
  30.     return envoltura
  31.  
  32. def sumar(x, y):
  33.     return x + y
  34.  
  35. @asincronismo
  36. def prueba():
  37.     r = yield Asincronica(sumar, (2, 3))
  38.     print(r)
  39.  
  40.     r = yield Asincronica(sumar, ('Python', ' 3.x'))
  41.     print(r)
  42.  
  43.     for n in range(10):
  44.         r = yield Asincronica(sumar, (n, n + 1))
  45.         print(r)
  46.  
  47.     print('Cierre')
  48.  
  49.  
  50. prueba()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement