immapp_utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Part of ImGui Bundle - MIT License - Copyright (c) 2022-2026 Pascal Thomet - https://github.com/pthom/imgui_bundle
  2. from typing import Callable, TypeVar, Any
  3. # Create type variables for the argument and return types of the function
  4. A = TypeVar("A", bound=Callable[..., Any])
  5. def static(**kwargs: Any) -> Callable[[A], A]:
  6. """A decorator that adds static variables to a function
  7. :param kwargs: list of static variables to add
  8. :return: decorated function
  9. Example:
  10. @static(x=0, y=0)
  11. def my_function():
  12. # static vars are stored as attributes of "my_function"
  13. # we use static as a more readable synonym.
  14. static = my_function
  15. static.x += 1
  16. static.y += 2
  17. print(f"{static.f.x}, {static.f.x}")
  18. invoking f three times would print 1, 2 then 2, 4, then 3, 6
  19. Static variables are similar to global variables, with the same shortcomings!
  20. Use them only in small scripts, not in production code!
  21. """
  22. def decorator(func: A) -> A:
  23. for key, value in kwargs.items():
  24. setattr(func, key, value)
  25. return func
  26. return decorator
  27. def run_anon_block(function: Callable[[], None]) -> None:
  28. """Decorator for anonymous block
  29. This enables you to emulate CC++ anonymous blocks.
  30. In the example below, _win_code() is an anonymous block which is evaluated right after its definition.
  31. Its presence makes it possible to indent parts of the code (for example, the code responsible for the widgets
  32. inside a window)
  33. imgui.begin("My window")
  34. @run_anon_block
  35. def _win_code():
  36. imgui.text("What is your name")
  37. changed_f, first_name = imgui.input_text("First name")
  38. changed_l, last_name = imgui.input_text("Last name")
  39. # ...
  40. imgui.end()
  41. """
  42. function()
  43. # Create type variables for the argument and return types of the function
  44. AnyCallable = TypeVar("AnyCallable", bound=Callable[..., Any])