reactive.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """
  2. Prompt_toolkit is designed a way that the amount of changing state is reduced
  3. to a minimum. Where possible, code is written in a pure functional way. In
  4. general, this results in code where the flow is very easy to follow: the value
  5. of a variable can be deducted from its first assignment.
  6. However, often, practicality and performance beat purity and some classes still
  7. have a changing state. In order to not having to care too much about
  8. transferring states between several components we use some reactive
  9. programming. Actually some kind of data binding.
  10. We introduce two types:
  11. - Filter: for binding a boolean state. They can be chained using & and |
  12. operators. Have a look in the ``filters`` module. Resolving the actual value
  13. of a filter happens by calling it.
  14. - Integer: for binding integer values. Reactive operations (like addition and
  15. substraction) are not suppported. Resolving the actual value happens by
  16. casting it to int, like ``int(integer)``. This way, it is possible to use
  17. normal integers as well for static values.
  18. """
  19. from __future__ import unicode_literals
  20. from abc import ABCMeta, abstractmethod
  21. from six import with_metaclass
  22. class Integer(with_metaclass(ABCMeta, object)):
  23. """
  24. Reactive integer -- anything that can be resolved to an ``int``.
  25. """
  26. @abstractmethod
  27. def __int__(self):
  28. return 0
  29. @classmethod
  30. def from_callable(cls, func):
  31. """
  32. Create an Integer-like object that calls the given function when it is
  33. resolved to an int.
  34. """
  35. return _IntegerFromCallable(func)
  36. Integer.register(int)
  37. class _IntegerFromCallable(Integer):
  38. def __init__(self, func=0):
  39. self.func = func
  40. def __repr__(self):
  41. return 'Integer.from_callable(%r)' % self.func
  42. def __int__(self):
  43. return int(self.func())