Can I stash instances of things and expect it to work? #5187
-
In 1st party textualize-written code, I see patterns like this used a lot: class Foo(Widget):
def compose(self):
yield Select(id='foo')
def somewhere_else(self):
control = self.query_one('#foo')
... Is there any reason the following wont work instead? (e.g. the widget instance references arent stable-ly going to be the same object as what's on screen) class Foo(Widget):
def __init__(self):
self.select = Select(id='foo')
def compose(self):
yield self.select
def somewhere_else(self):
control = self.select
... I've started doing this to avoid the query system and it seems to JustWork. In my current cases, I can usually statically know the set of screens/widgets/etc that a given thing is going to produce given the contructor args for the object in question. And by doing so, i can have stronger typing on the existence of these objects. In fact, even with things that are more dynamics, like mutable lists of controls, it seems easier to append to a typed list of controls than to formulate a query and get back an unknown collection of widgets. I'd perhaps even resort to this pattern for non-direct descendant objects by passing them into the constructor of my e.g. widget rather than querying for them, for all the same reasons. Although obviously this has a cost and i'm sure there are some scenarios where the query system would be more ergonomic. tl;dr am i missing something fundamental about reactivity or whatnot where doing this is going to bite me versus using the query system? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Sure, you can. But I would avoid it for a few reasons.
Note that if you do |
Beta Was this translation helpful? Give feedback.
If you recompose, the current widgets will be removed, including any attribute you have stored. Adding a widget after it has been removed, will break unfortunately.
query_one should never return
None
, so no assert should be required.query_one is generally fast enough for it to not be a concern, however you could use get_child_by_id for the fastest lookup.