Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 2.1KB

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import asyncio
  2. import types
  3. def name_that_thing(thing):
  4. """
  5. Returns either the function/class path or just the object's repr
  6. """
  7. # Instance method
  8. if hasattr(thing, "im_class"):
  9. # Mocks will recurse im_class forever
  10. if hasattr(thing, "mock_calls"):
  11. return "<mock>"
  12. return name_that_thing(thing.im_class) + "." + thing.im_func.func_name
  13. # Other named thing
  14. if hasattr(thing, "__name__"):
  15. if hasattr(thing, "__class__") and not isinstance(
  16. thing, (types.FunctionType, types.MethodType)
  17. ):
  18. if thing.__class__ is not type and not issubclass(thing.__class__, type):
  19. return name_that_thing(thing.__class__)
  20. if hasattr(thing, "__self__"):
  21. return "%s.%s" % (thing.__self__.__module__, thing.__self__.__name__)
  22. if hasattr(thing, "__module__"):
  23. return "%s.%s" % (thing.__module__, thing.__name__)
  24. # Generic instance of a class
  25. if hasattr(thing, "__class__"):
  26. return name_that_thing(thing.__class__)
  27. return repr(thing)
  28. async def await_many_dispatch(consumer_callables, dispatch):
  29. """
  30. Given a set of consumer callables, awaits on them all and passes results
  31. from them to the dispatch awaitable as they come in.
  32. """
  33. # Call all callables, and ensure all return types are Futures
  34. tasks = [
  35. asyncio.ensure_future(consumer_callable())
  36. for consumer_callable in consumer_callables
  37. ]
  38. try:
  39. while True:
  40. # Wait for any of them to complete
  41. await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
  42. # Find the completed one(s), yield results, and replace them
  43. for i, task in enumerate(tasks):
  44. if task.done():
  45. result = task.result()
  46. await dispatch(result)
  47. tasks[i] = asyncio.ensure_future(consumer_callables[i]())
  48. finally:
  49. # Make sure we clean up tasks on exit
  50. for task in tasks:
  51. task.cancel()
  52. try:
  53. await task
  54. except asyncio.CancelledError:
  55. pass