Replies: 1 comment
-
Also i wonder if those "scope-wide" singletons can come in handy in other situations when you need to isolate context on different levels in a "object-oriented style". Especially when you deal with descriptors. Say, you need bindable user-scope variables encapsulated with some logic: @binding.bindable_dataclass
class UserContext(metaclass=SessionScopeSingleton):
x: int = 0
def inc(self):
self.x += 1
@ui.page('/user_context')
def demo():
user_context = UserContext()
ui.label().bind_text_from(user_context, 'x')
ui.button('Increment', on_click=user_context.inc) Worth mentioning: you can operate the context in many classes distributed across your code base, it doesn't have to be one huge class. Is there any better (cleaner) way to achieve such goals? Maybe there is an existing option already? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Recently I faced quite an amusing bug in my application, that was caused by misuse of a global scoped
ui.refreshable
.So I went to re-read the docs and try to realize what I might have missed on my first reading. The docs say:
Then, when discussing the demo:
What the docs don't say explicitly, is that the state is also shared between all browsers/sessions (meaning users)!
I know, I know, what else the word "global" can mean... Also, yes, the docs explicitly say "... every UI shares the same state". And still, I have a feeling I'm not the only one nooby who didn't immediately get it right. So maybe (just maybe) some extra words on users-wide ui state sharing would be a nice addition.
Then i wondered if there is a simple way to make it work like i at first supposed it did: share ui state between tabs, but not sessions. I found no built-in solution (at least no documented). So, for those wondering with me, here is what i came up with: a combination of Local scope (variant B) recipe and somewhat a session-wide singleton metaclass:
Now
clock
is the same instance for everyclient
utilizing the samesession
. So ui state will be shared across all tabs of a browser (but not beyond).By the way, one insidious thing concerning Local scope (variant B) and the corresponding demo. If i make a (seemingly) innocent changes to the code:
The state "isolation" breaks in a way that might surprise a clueless NiceGUI enjoyer. Namely, pressing button on the first (in order of loading) tab changes the value on the second.
Sure, it's a bit artificial example. Not saying the problem is
refreshable
API. However, knowing from the documentation that you should never separate access to arefreshable
as a class property from its invocation might save you some time investigating strange code behavior.Beta Was this translation helpful? Give feedback.
All reactions