Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
wip attempt at simplifying Module() API and implementation
- Loading branch information
Showing
5 changed files
with
130 additions
and
156 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
__all__ = ("namespace_context",) | ||
|
||
from contextlib import contextmanager | ||
from contextvars import ContextVar, Token | ||
|
||
from typing import Union, Optional | ||
|
||
_current_namespace: ContextVar[Optional[str]] = ContextVar( | ||
"current_namespace", default=None | ||
) | ||
|
||
|
||
@contextmanager | ||
def namespace_context(ns: str): | ||
""" | ||
Set a namespace for the duration of the context. | ||
""" | ||
token: Token[Union[str, None]] = _current_namespace.set(ns) | ||
try: | ||
yield | ||
finally: | ||
_current_namespace.reset(token) | ||
|
||
|
||
# Protect id's from being namespaced twice. | ||
class Namespaced(str): | ||
pass | ||
|
||
|
||
def namespaced(id: str) -> Union[str, Namespaced]: | ||
""" | ||
Namespace an ID based on the current ``Module()``'s namespace. | ||
Parameters | ||
---------- | ||
id | ||
The ID to namespace. | ||
Warning | ||
------- | ||
This is only provided so that htmltools can use it to namespace ids within a | ||
``Module()`` UI function. | ||
""" | ||
ns = _current_namespace.get() | ||
if ns is None or isinstance(id, Namespaced): | ||
return id | ||
else: | ||
return Namespaced(ns + "-" + id) |
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
Oops, something went wrong.