Created
June 18, 2020 17:49
-
-
Save Lateasusual/8e02a2c5366d2332ceee7adbfb9a7395 to your computer and use it in GitHub Desktop.
An example use of a multi-purpose context manager class (with some tricks from withhacks)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imgui | |
from sys import _getframe, settrace | |
class Panel: | |
""" | |
This is... not a particularly *useful* example, but it allows us to have one Panel class which can be used for drawing *without* inheritance. See below for examples | |
""" | |
class Closed(Exception): | |
... | |
def __init__(self, title, closable=False, is_open=True, default_size=(520, 600)): | |
self.title = title | |
self.closable = closable | |
self.is_open = is_open | |
self.default_size = default_size | |
def __enter__(self): | |
imgui.set_window_size(*self.default_size, imgui.FIRST_USE_EVER) | |
if self.is_open: | |
_, self.is_open = imgui.begin(self.title, self.closable) | |
return self | |
else: | |
settrace(lambda *args, **kwargs: None) | |
frame = _getframe(1) | |
frame.f_trace = self.trace | |
def trace(self, frame, event, arg): | |
raise self.Closed() | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if exc_type == self.Closed: | |
return True | |
imgui.end() | |
return False | |
def __draw__(self): | |
with self: | |
self.draw() | |
def draw(self): | |
... | |
# Panel must be drawn by instantiating it and calling panel.draw() | |
class ExamplePanel(Panel): | |
def draw(self): | |
imgui.text("Panel with inheritance!") | |
# Can be inserted directly into your draw method | |
def draw_a_panel(): | |
with Panel("Hello Panel!"): | |
imgui.text("Panel just made up on the spot!") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment