Reputation: 61084
I know the phrasing of this question may be a bit off, but please allow me explain. It's also a general python question, but I'm using a specific case to explain it
[I'm working with a group of stylesheets or themes from dash_bootstrap_components. And now I've stumbled upon a more general python problem that I've been wondering about for a while. You can set up a Dash app with the following snippet where the last line specifies a stylesheet:
from jupyter_dash import JupyterDash
import dash_bootstrap_components as dbc
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
But let's say that I'd like to assign that theme using a variable name and not its explicit name SLATE
- for example when setting another stylesheet or letting the particular stylesheet be an option for the users to select. How can I loop through the module or select a theme using a variable name instead of SLATE
?
The post How to get a list of variables in specific Python module? shows how to loop through a module like this using:
[item for item in dir(dbc.themes) if not item.startswith("__")]
But I'd still need to select the theme somehow. These are some of the things I've tried:
myVar = 'SLATE'
themed_app = JupyterDash(external_stylesheets=[dbc.themes[myVar])
I do realize that it's a lack of basic python understanding that's the problem here, but I would really like to know why this fails and what could be done instead.
Upvotes: 0
Views: 198
Reputation: 780949
Use getattr
to access an attribute dynamically.
themed_app = JupyterDash(external_stylesheets=[getattr(dbc.themes, myVar)])
Upvotes: 2
Reputation: 1068
You can use eval
as another solution to access dynamically
var = "SLATE"
sheet = f"dbc.themes.{var}"
themed_app = JupyterDash(external_stylesheets=[eval(sheet)])
Upvotes: 1