response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Test that st.write displays altair charts.
def test_display_altair(app: Page): """Test that st.write displays altair charts.""" altair_elements = app.get_by_test_id("stArrowVegaLiteChart") expect(altair_elements).to_have_count(1)
Test that st.write displays plotly charts.
def test_display_plotly(app: Page): """Test that st.write displays plotly charts.""" plotly_elements = app.locator(".stPlotlyChart") expect(plotly_elements).to_have_count(1)
Test that st.write displays graphviz charts.
def test_display_graphviz(app: Page): """Test that st.write displays graphviz charts.""" plotly_elements = app.get_by_test_id("stGraphVizChart") expect(plotly_elements).to_have_count(1)
Test that st.write displays pydeck charts.
def test_display_pydeck_chart(app: Page): """Test that st.write displays pydeck charts.""" pydeck_elements = app.get_by_test_id("stDeckGlJsonChart") expect(pydeck_elements).to_have_count(1)
Test that components.html can be imported and used
def test_components_html(app: Page): """Test that components.html can be imported and used""" _select_component(app, "componentsHtml") _expect_no_exception(app) iframe = app.frame_locator("iframe") expect(iframe.locator("div", has_text="Hello World!")).to_be_attached()
Test that the ace component renders
def test_ace(app: Page): """Test that the ace component renders""" _select_component(app, "ace") _expect_no_exception(app)
Test that the aggrid component renders
def test_aggrid(app: Page): """Test that the aggrid component renders""" _select_component(app, "aggrid") _expect_no_exception(app)
Test that the ace component renders
def test_antd(app: Page): """Test that the ace component renders""" _select_component(app, "antd") _expect_no_exception(app)
Test that the autorefresh component renders
def test_autorefresh(app: Page): """Test that the autorefresh component renders""" _select_component(app, "autorefresh") _expect_no_exception(app)
Test that the chat component renders
def test_chat(app: Page): """Test that the chat component renders""" _select_component(app, "chat")
Test that the echarts component renders
def test_echarts(app: Page): """Test that the echarts component renders""" _select_component(app, "echarts") _expect_no_exception(app)
Test that the extra-strealit-components component renders
def test_extra_streamlit_components(app: Page): """Test that the extra-strealit-components component renders""" _select_component(app, "extraStreamlitComponents") _expect_no_exception(app)
Test that the folium component renders
def test_folium(app: Page): """Test that the folium component renders""" _select_component(app, "folium")
Test that the lottie component renders
def test_lottie(app: Page): """Test that the lottie component renders""" _select_component(app, "lottie") _expect_no_exception(app)
Test that the option-menu component renders
def test_option_menu(app: Page): """Test that the option-menu component renders""" _select_component(app, "optionMenu") _expect_no_exception(app)
Test that the url-fragment component renders
def test_url_fragment(app: Page): """Test that the url-fragment component renders""" _select_component(app, "urlFragment") _expect_no_exception(app)
Test that the main script is loaded on initial page load.
def test_loads_main_script_on_initial_page_load(app: Page): """Test that the main script is loaded on initial page load.""" expect(app.get_by_test_id("stHeading")).to_contain_text("Main Page")
Test that the sidebar nav is rendered correctly.
def test_renders_sidebar_nav_correctly( themed_app: Page, assert_snapshot: ImageCompareFunction ): """Test that the sidebar nav is rendered correctly.""" assert_snapshot(themed_app.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav")
Test that we can switch between pages by clicking on sidebar links.
def test_can_switch_between_pages_by_clicking_on_sidebar_links(app: Page): """Test that we can switch between pages by clicking on sidebar links.""" app.get_by_test_id("stSidebarNav").locator("a").nth(1).click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading")).to_contain_text("Page 2")
Test that we can navigate to a page directly via URL.
def test_supports_navigating_to_page_directly_via_url(page: Page, app_port: int): """Test that we can navigate to a page directly via URL.""" page.goto(f"http://localhost:{app_port}/page2") wait_for_app_loaded(page) expect(page.get_by_test_id("stHeading")).to_contain_text("Page 2")
Test that we can switch between pages and edit widgets.
def test_can_switch_between_pages_and_edit_widgets(app: Page): """Test that we can switch between pages and edit widgets.""" slider = app.locator('.stSlider [role="slider"]') slider.click() slider.press("ArrowRight") wait_for_app_run(app, wait_delay=500) app.get_by_test_id("stSidebarNav").locator("a").nth(2).click() wait_for_app_run(app, wait_delay=1000) expect(app.get_by_test_id("stHeading")).to_contain_text("Page 3") expect(app.get_by_test_id("stMarkdown")).to_contain_text("x is 0") slider.click() slider.press("ArrowRight") wait_for_app_run(app) expect(app.get_by_test_id("stMarkdown")).to_contain_text("x is 1")
Test that we can switch to the first page with a duplicate name.
def test_can_switch_to_the_first_page_with_a_duplicate_name(app: Page): """Test that we can switch to the first page with a duplicate name.""" app.get_by_test_id("stSidebarNav").locator("a").nth(3).click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading")).to_contain_text("Page 4")
Test that we can switch to the second page with a duplicate name.
def test_can_switch_to_the_second_page_with_a_duplicate_name(app: Page): """Test that we can switch to the second page with a duplicate name.""" app.get_by_test_id("stSidebarNav").locator("a").nth(4).click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading")).to_contain_text("Page 5")
Test that we run the first page with a duplicate name if navigating via URL.
def test_runs_the_first_page_with_a_duplicate_name_if_navigating_via_url( page: Page, app_port: int ): """Test that we run the first page with a duplicate name if navigating via URL.""" page.goto(f"http://localhost:{app_port}/page_with_duplicate_name") wait_for_app_loaded(page) expect(page.get_by_test_id("stHeading")).to_contain_text("Page 4")
Test that we show a not found dialog if the page doesn't exist.
def test_show_not_found_dialog(page: Page, app_port: int): """Test that we show a not found dialog if the page doesn't exist.""" page.goto(f"http://localhost:{app_port}/not_a_page") wait_for_app_loaded(page) expect(page.locator('[role="dialog"]')).to_contain_text("Page not found")
Test that we handle expand/collapse of MPA nav correctly.
def test_handles_expand_collapse_of_mpa_nav_correctly( page: Page, app_port: int, assert_snapshot: ImageCompareFunction ): """Test that we handle expand/collapse of MPA nav correctly.""" page.goto(f"http://localhost:{app_port}/page_7") wait_for_app_loaded(page) separator = page.get_by_test_id("stSidebarNavSeparator") svg = separator.locator("svg") expect(svg).to_be_visible() # Expand the nav svg.click(force=True) # We apply a quick timeout here so that the UI has some time to # adjust for the screenshot after the click page.wait_for_timeout(250) assert_snapshot( page.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav_expanded" ) # Collapse the nav svg.click(force=True) page.wait_for_timeout(250) assert_snapshot( page.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav_collapsed" ) # Expand the nav again svg.click(force=True) page.wait_for_timeout(250) assert_snapshot( page.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav_expanded" )
Test that we can switch between pages by triggering st.switch_page.
def test_switch_page(app: Page): """Test that we can switch between pages by triggering st.switch_page.""" # Click the button to trigger st.switch_page using relative path app.get_by_test_id("stButton").nth(0).locator("button").first.click() wait_for_app_run(app) # Check that we are on the correct page expect(app.get_by_test_id("stHeading")).to_contain_text("Page 2") # st.switch_page using relative path & leading / app.get_by_test_id("baseButton-secondary").click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading")).to_contain_text("Page 6") # st.switch_page using relative path & leading ./ app.get_by_test_id("baseButton-secondary").click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading")).to_contain_text("Main Page")
Test that query params are removed when navigating via st.switch_page
def test_switch_page_removes_query_params(page: Page, app_port: int): """Test that query params are removed when navigating via st.switch_page""" # Start at main page with query params page.goto(f"http://localhost:{app_port}/?foo=bar") wait_for_app_loaded(page) # Trigger st.switch_page page.get_by_test_id("stButton").nth(0).locator("button").first.click() wait_for_app_loaded(page) # Check that query params don't persist expect(page).to_have_url(f"http://localhost:{app_port}/page2")
Test that query params are removed when swapping pages
def test_removes_query_params_when_swapping_pages(page: Page, app_port: int): """Test that query params are removed when swapping pages""" page.goto(f"http://localhost:{app_port}/page_7?foo=bar") wait_for_app_loaded(page) page.get_by_test_id("stSidebarNav").locator("a").nth(2).click() wait_for_app_loaded(page) expect(page).to_have_url(f"http://localhost:{app_port}/page3")
Test that query params are removed when swapping pages
def test_removes_non_embed_query_params_when_swapping_pages(page: Page, app_port: int): """Test that query params are removed when swapping pages""" page.goto( f"http://localhost:{app_port}/page_7?foo=bar&embed=True&embed_options=show_toolbar&embed_options=show_colored_line" ) wait_for_app_loaded(page) page.get_by_test_id("stSidebarNav").locator("a").nth(2).click() wait_for_app_loaded(page) expect(page).to_have_url( f"http://localhost:{app_port}/page3?embed=true&embed_options=show_toolbar&embed_options=show_colored_line" )
Configure client.showSidebarNavigation=False.
def configure_show_sidebar_nav(): """Configure client.showSidebarNavigation=False.""" # We need to do this in a package scope fixture to ensure that its applied # before the app server is started. os.environ["STREAMLIT_CLIENT_SHOW_SIDEBAR_NAVIGATION"] = "False" yield del os.environ["STREAMLIT_CLIENT_SHOW_SIDEBAR_NAVIGATION"]
Test that client.showSidebarNavigation=False hides the sidebar.
def test_hides_sidebar_nav(app: Page, configure_show_sidebar_nav): """Test that client.showSidebarNavigation=False hides the sidebar.""" expect(app.get_by_test_id("stSidebar")).not_to_be_attached()
Test that page link appears as expected in main.
def test_page_links_in_main( themed_app: Page, configure_show_sidebar_nav, assert_snapshot: ImageCompareFunction ): """Test that page link appears as expected in main.""" expect(themed_app.get_by_test_id("stSidebar")).not_to_be_attached() page_links = themed_app.get_by_test_id("stPageLink-NavLink") expect(page_links).to_have_count(5) # Selected page assert_snapshot(page_links.nth(0), name="current-page-link") page_links.nth(0).hover() assert_snapshot(page_links.nth(0), name="current-page-link-hover") # Non-selected page assert_snapshot(page_links.nth(1), name="page-link") page_links.nth(1).hover() assert_snapshot(page_links.nth(1), name="page-link-hover") # Disabled page assert_snapshot(page_links.nth(2), name="page-link-disabled")
Test that page link appears as expected in sidebar.
def test_page_links_in_sidebar( themed_app: Page, configure_show_sidebar_nav, assert_snapshot: ImageCompareFunction ): """Test that page link appears as expected in sidebar.""" page_links = themed_app.get_by_test_id("stPageLink-NavLink") # Navigate to Page 4 page_links.nth(3).click() wait_for_app_run(themed_app) page_links = themed_app.get_by_test_id("stPageLink-NavLink") expect(page_links).to_have_count(5) # Selected page assert_snapshot(page_links.nth(3), name="current-page-link-sidebar") page_links.nth(3).hover() assert_snapshot(page_links.nth(3), name="current-page-link-sidebar-hover") # Non-selected page assert_snapshot(page_links.nth(0), name="page-link-sidebar") page_links.nth(0).hover() assert_snapshot(page_links.nth(0), name="page-link-sidebar-hover") # Disabled page assert_snapshot(page_links.nth(4), name="page-link-sidebar-disabled")
Test that page link href set properly.
def test_page_link_href( app: Page, configure_show_sidebar_nav, ): """Test that page link href set properly.""" page_links = app.get_by_test_id("stPageLink-NavLink") expect(page_links.nth(0)).to_have_attribute("href", "mpa_configure_sidebar") expect(page_links.nth(1)).to_have_attribute("href", "page2") expect(page_links.nth(2)).to_have_attribute("href", "page3") expect(page_links.nth(3)).to_have_attribute("href", "page_with_duplicate_name")
Converts snake_case to UpperCamelCase. Example ------- foo_bar -> FooBar
def to_upper_camel_case(snake_case_str: str) -> str: """Converts snake_case to UpperCamelCase. Example ------- foo_bar -> FooBar """ return "".join(map(str.title, snake_case_str.split("_")))
Converts snake_case to lowerCamelCase. Example ------- foo_bar -> fooBar fooBar -> foobar
def to_lower_camel_case(snake_case_str: str) -> str: """Converts snake_case to lowerCamelCase. Example ------- foo_bar -> fooBar fooBar -> foobar """ words = snake_case_str.split("_") if len(words) > 1: capitalized = [w.title() for w in words] capitalized[0] = words[0] return "".join(capitalized) else: return snake_case_str
Converts UpperCamelCase and lowerCamelCase to snake_case. Examples -------- fooBar -> foo_bar BazBang -> baz_bang
def to_snake_case(camel_case_str: str) -> str: """Converts UpperCamelCase and lowerCamelCase to snake_case. Examples -------- fooBar -> foo_bar BazBang -> baz_bang """ s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_case_str) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
Apply a conversion function to all keys in a dict. Parameters ---------- func : callable The function to apply. Takes a str and returns a str. in_dict : dict The dictionary to convert. If some value in this dict is itself a dict, it also gets recursively converted. Returns ------- dict A new dict with all the contents of `in_dict`, but with the keys converted by `func`.
def convert_dict_keys( func: Callable[[str], str], in_dict: dict[Any, Any] ) -> dict[Any, Any]: """Apply a conversion function to all keys in a dict. Parameters ---------- func : callable The function to apply. Takes a str and returns a str. in_dict : dict The dictionary to convert. If some value in this dict is itself a dict, it also gets recursively converted. Returns ------- dict A new dict with all the contents of `in_dict`, but with the keys converted by `func`. """ out_dict = dict() for k, v in in_dict.items(): converted_key = func(k) if type(v) is dict: out_dict[converted_key] = convert_dict_keys(func, v) else: out_dict[converted_key] = v return out_dict
Print a message to the terminal using click if available, else print using the built-in print function. You can provide any keyword arguments that click.secho supports.
def print_to_cli(message: str, **kwargs) -> None: """Print a message to the terminal using click if available, else print using the built-in print function. You can provide any keyword arguments that click.secho supports. """ try: import click click.secho(message, **kwargs) except ImportError: print(message, flush=True)
Style a message using click if available, else return the message unchanged. You can provide any keyword arguments that click.style supports.
def style_for_cli(message: str, **kwargs) -> str: """Style a message using click if available, else return the message unchanged. You can provide any keyword arguments that click.style supports. """ try: import click return click.style(message, **kwargs) except ImportError: return message
Parse argument strings from all outer parentheses in a line of code. Parameters ---------- line : str A line of code Returns ------- list of strings Contents of the outer parentheses Example ------- >>> line = 'foo(bar, baz), "a", my(func)' >>> extract_args(line) ['bar, baz', 'func']
def extract_args(line: str) -> list[str]: """Parse argument strings from all outer parentheses in a line of code. Parameters ---------- line : str A line of code Returns ------- list of strings Contents of the outer parentheses Example ------- >>> line = 'foo(bar, baz), "a", my(func)' >>> extract_args(line) ['bar, baz', 'func'] """ stack = 0 startIndex = None results = [] for i, c in enumerate(line): if c == "(": if stack == 0: startIndex = i + 1 stack += 1 elif c == ")": stack -= 1 if stack == 0: results.append(line[startIndex:i]) return results
Parse arguments from a stringified arguments list inside parentheses Parameters ---------- args : list A list where it's size matches the expected number of parsed arguments line : str Stringified line of code with method arguments inside parentheses Returns ------- list of strings Parsed arguments Example ------- >>> line = 'foo(bar, baz, my(func, tion))' >>> >>> get_method_args_from_code(range(0, 3), line) ['bar', 'baz', 'my(func, tion)']
def get_method_args_from_code(args: list[Any], line: str) -> list[str]: """Parse arguments from a stringified arguments list inside parentheses Parameters ---------- args : list A list where it's size matches the expected number of parsed arguments line : str Stringified line of code with method arguments inside parentheses Returns ------- list of strings Parsed arguments Example ------- >>> line = 'foo(bar, baz, my(func, tion))' >>> >>> get_method_args_from_code(range(0, 3), line) ['bar', 'baz', 'my(func, tion)'] """ line_args = extract_args(line)[0] # Split arguments, https://stackoverflow.com/a/26634150 if len(args) > 1: inputs = re.split(r",\s*(?![^(){}[\]]*\))", line_args) assert len(inputs) == len(args), "Could not split arguments" else: inputs = [line_args] return inputs
Convert input into color tuple of type (int, int, int, int).
def to_int_color_tuple(color: MaybeColor) -> IntColorTuple: """Convert input into color tuple of type (int, int, int, int).""" color_tuple = _to_color_tuple( color, rgb_formatter=_int_formatter, alpha_formatter=_int_formatter, ) return cast(IntColorTuple, color_tuple)
Convert input into a CSS-compatible color that Vega can use. Inputs must be a hex string, rgb()/rgba() string, or a color tuple. Inputs may not be a CSS color name, other CSS color function (like "hsl(...)"), etc. See tests for more info.
def to_css_color(color: MaybeColor) -> Color: """Convert input into a CSS-compatible color that Vega can use. Inputs must be a hex string, rgb()/rgba() string, or a color tuple. Inputs may not be a CSS color name, other CSS color function (like "hsl(...)"), etc. See tests for more info. """ if is_css_color_like(color): return cast(Color, color) if is_color_tuple_like(color): ctuple = cast(ColorTuple, color) ctuple = _normalize_tuple(ctuple, _int_formatter, _float_formatter) if len(ctuple) == 3: return f"rgb({ctuple[0]}, {ctuple[1]}, {ctuple[2]})" elif len(ctuple) == 4: c4tuple = cast(MixedRGBAColorTuple, ctuple) return f"rgba({c4tuple[0]}, {c4tuple[1]}, {c4tuple[2]}, {c4tuple[3]})" raise InvalidColorException(color)
Check whether the input looks like something Vega can use. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown. NOTE: We only accept hex colors and color tuples as user input. So do not use this function to validate user input! Instead use is_hex_color_like and is_color_tuple_like.
def is_css_color_like(color: MaybeColor) -> bool: """Check whether the input looks like something Vega can use. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown. NOTE: We only accept hex colors and color tuples as user input. So do not use this function to validate user input! Instead use is_hex_color_like and is_color_tuple_like. """ return is_hex_color_like(color) or _is_cssrgb_color_like(color)
Check whether the input looks like a hex color. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown.
def is_hex_color_like(color: MaybeColor) -> bool: """Check whether the input looks like a hex color. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown. """ return ( isinstance(color, str) and color.startswith("#") and color[1:].isalnum() # Alphanumeric and len(color) in {4, 5, 7, 9} )
Check whether the input looks like a CSS rgb() or rgba() color string. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown. NOTE: We only accept hex colors and color tuples as user input. So do not use this function to validate user input! Instead use is_hex_color_like and is_color_tuple_like.
def _is_cssrgb_color_like(color: MaybeColor) -> bool: """Check whether the input looks like a CSS rgb() or rgba() color string. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown. NOTE: We only accept hex colors and color tuples as user input. So do not use this function to validate user input! Instead use is_hex_color_like and is_color_tuple_like. """ return isinstance(color, str) and ( color.startswith("rgb(") or color.startswith("rgba(") )
Check whether the input looks like a tuple color. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown.
def is_color_tuple_like(color: MaybeColor) -> bool: """Check whether the input looks like a tuple color. This is meant to be lightweight, and not a definitive answer. The definitive solution is to try to convert and see if an error is thrown. """ return ( isinstance(color, (tuple, list)) and len(color) in {3, 4} and all(isinstance(c, (int, float)) for c in color) )
A fairly lightweight check of whether the input is a color. This isn't meant to be a definitive answer. The definitive solution is to try to convert and see if an error is thrown.
def is_color_like(color: MaybeColor) -> bool: """A fairly lightweight check of whether the input is a color. This isn't meant to be a definitive answer. The definitive solution is to try to convert and see if an error is thrown. """ return is_css_color_like(color) or is_color_tuple_like(color)
Convert a potential color to a color tuple. The exact type of color tuple this outputs is dictated by the formatter parameters. The R, G, B components are transformed by rgb_formatter, and the alpha component is transformed by alpha_formatter. For example, to output a (float, float, float, int) color tuple, set rgb_formatter to _float_formatter and alpha_formatter to _int_formatter.
def _to_color_tuple( color: MaybeColor, rgb_formatter: Callable[[float, MaybeColor], float], alpha_formatter: Callable[[float, MaybeColor], float], ): """Convert a potential color to a color tuple. The exact type of color tuple this outputs is dictated by the formatter parameters. The R, G, B components are transformed by rgb_formatter, and the alpha component is transformed by alpha_formatter. For example, to output a (float, float, float, int) color tuple, set rgb_formatter to _float_formatter and alpha_formatter to _int_formatter. """ if is_hex_color_like(color): hex_len = len(color) color_hex = cast(str, color) if hex_len == 4: r = 2 * color_hex[1] g = 2 * color_hex[2] b = 2 * color_hex[3] a = "ff" elif hex_len == 5: r = 2 * color_hex[1] g = 2 * color_hex[2] b = 2 * color_hex[3] a = 2 * color_hex[4] elif hex_len == 7: r = color_hex[1:3] g = color_hex[3:5] b = color_hex[5:7] a = "ff" elif hex_len == 9: r = color_hex[1:3] g = color_hex[3:5] b = color_hex[5:7] a = color_hex[7:9] else: raise InvalidColorException(color) try: color = int(r, 16), int(g, 16), int(b, 16), int(a, 16) except: raise InvalidColorException(color) if is_color_tuple_like(color): color_tuple = cast(ColorTuple, color) return _normalize_tuple(color_tuple, rgb_formatter, alpha_formatter) raise InvalidColorException(color)
Parse color tuple using the specified color formatters. The R, G, B components are transformed by rgb_formatter, and the alpha component is transformed by alpha_formatter. For example, to output a (float, float, float, int) color tuple, set rgb_formatter to _float_formatter and alpha_formatter to _int_formatter.
def _normalize_tuple( color: ColorTuple, rgb_formatter: Callable[[float, MaybeColor], float], alpha_formatter: Callable[[float, MaybeColor], float], ) -> ColorTuple: """Parse color tuple using the specified color formatters. The R, G, B components are transformed by rgb_formatter, and the alpha component is transformed by alpha_formatter. For example, to output a (float, float, float, int) color tuple, set rgb_formatter to _float_formatter and alpha_formatter to _int_formatter. """ if len(color) == 3: r = rgb_formatter(color[0], color) g = rgb_formatter(color[1], color) b = rgb_formatter(color[2], color) return r, g, b elif len(color) == 4: color_4tuple = cast(Color4Tuple, color) r = rgb_formatter(color_4tuple[0], color_4tuple) g = rgb_formatter(color_4tuple[1], color_4tuple) b = rgb_formatter(color_4tuple[2], color_4tuple) alpha = alpha_formatter(color_4tuple[3], color_4tuple) return r, g, b, alpha raise InvalidColorException(color)
Convert a color component (float or int) to an int from 0 to 255. Anything too small will become 0, and anything too large will become 255.
def _int_formatter(component: float, color: MaybeColor) -> int: """Convert a color component (float or int) to an int from 0 to 255. Anything too small will become 0, and anything too large will become 255. """ if isinstance(component, float): component = int(component * 255) if isinstance(component, int): return min(255, max(component, 0)) raise InvalidColorException(color)
Convert a color component (float or int) to a float from 0.0 to 1.0. Anything too small will become 0.0, and anything too large will become 1.0.
def _float_formatter(component: float, color: MaybeColor) -> float: """Convert a color component (float or int) to a float from 0.0 to 1.0. Anything too small will become 0.0, and anything too large will become 1.0. """ if isinstance(component, int): component = component / 255.0 if isinstance(component, float): return min(1.0, max(component, 0.0)) raise InvalidColorException(color)
Set config option. Run `streamlit config show` in the terminal to see all available options. This is an internal API. The public `st.set_option` API is implemented in `set_user_option`. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. value The new value to assign to this config option. where_defined : str Tells the config system where this was set.
def set_option(key: str, value: Any, where_defined: str = _USER_DEFINED) -> None: """Set config option. Run `streamlit config show` in the terminal to see all available options. This is an internal API. The public `st.set_option` API is implemented in `set_user_option`. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. value The new value to assign to this config option. where_defined : str Tells the config system where this was set. """ with _config_lock: # Ensure that our config files have been parsed. get_config_options() _set_option(key, value, where_defined)
Set config option. Currently, only the following config options can be set within the script itself: * client.caching * client.displayEnabled * deprecation.* Calling with any other options will raise StreamlitAPIException. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. value The new value to assign to this config option.
def set_user_option(key: str, value: Any) -> None: """Set config option. Currently, only the following config options can be set within the script itself: * client.caching * client.displayEnabled * deprecation.* Calling with any other options will raise StreamlitAPIException. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. value The new value to assign to this config option. """ try: opt = _config_options_template[key] except KeyError as ke: raise StreamlitAPIException(f"Unrecognized config option: {key}") from ke if opt.scriptable: set_option(key, value) return raise StreamlitAPIException( "{key} cannot be set on the fly. Set as command line option, e.g. streamlit run script.py --{key}, or in config.toml instead.".format( key=key ) )
Return the current value of a given Streamlit config option. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal.
def get_option(key: str) -> Any: """Return the current value of a given Streamlit config option. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. """ with _config_lock: config_options = get_config_options() if key not in config_options: raise RuntimeError('Config key "%s" not defined.' % key) return config_options[key].value
Get all of the config options for the given section. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- section : str The name of the config section to fetch options for. Returns ------- dict[str, Any] A dict mapping the names of the options in the given section (without the section name as a prefix) to their values.
def get_options_for_section(section: str) -> dict[str, Any]: """Get all of the config options for the given section. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- section : str The name of the config section to fetch options for. Returns ------- dict[str, Any] A dict mapping the names of the options in the given section (without the section name as a prefix) to their values. """ with _config_lock: config_options = get_config_options() options_for_section = {} for option in config_options.values(): if option.section == section: options_for_section[option.name] = option.value return options_for_section
Create a config section and store it globally in this module.
def _create_section(section: str, description: str) -> None: """Create a config section and store it globally in this module.""" assert section not in _section_descriptions, ( 'Cannot define section "%s" twice.' % section ) _section_descriptions[section] = description
Create a ConfigOption and store it globally in this module. There are two ways to create a ConfigOption: (1) Simple, constant config options are created as follows: _create_option('section.optionName', description = 'Put the description here.', default_val = 12345) (2) More complex, programmable config options use decorator syntax to resolve their values at runtime: @_create_option('section.optionName') def _section_option_name(): """Put the description here.""" return 12345 To achieve this sugar, _create_option() returns a *callable object* of type ConfigObject, which then decorates the function. NOTE: ConfigObjects call their evaluation functions *every time* the option is requested. To prevent this, use the `streamlit.util.memoize` decorator as follows: @_create_option('section.memoizedOptionName') @util.memoize def _section_memoized_option_name(): """Put the description here.""" (This function is only called once.) """ return 12345
def _create_option( key: str, description: str | None = None, default_val: Any | None = None, scriptable: bool = False, visibility: str = "visible", deprecated: bool = False, deprecation_text: str | None = None, expiration_date: str | None = None, replaced_by: str | None = None, type_: type = str, sensitive: bool = False, ) -> ConfigOption: '''Create a ConfigOption and store it globally in this module. There are two ways to create a ConfigOption: (1) Simple, constant config options are created as follows: _create_option('section.optionName', description = 'Put the description here.', default_val = 12345) (2) More complex, programmable config options use decorator syntax to resolve their values at runtime: @_create_option('section.optionName') def _section_option_name(): """Put the description here.""" return 12345 To achieve this sugar, _create_option() returns a *callable object* of type ConfigObject, which then decorates the function. NOTE: ConfigObjects call their evaluation functions *every time* the option is requested. To prevent this, use the `streamlit.util.memoize` decorator as follows: @_create_option('section.memoizedOptionName') @util.memoize def _section_memoized_option_name(): """Put the description here.""" (This function is only called once.) """ return 12345 ''' option = ConfigOption( key, description=description, default_val=default_val, scriptable=scriptable, visibility=visibility, deprecated=deprecated, deprecation_text=deprecation_text, expiration_date=expiration_date, replaced_by=replaced_by, type_=type_, sensitive=sensitive, ) assert ( option.section in _section_descriptions ), 'Section "{}" must be one of {}.'.format( option.section, ", ".join(_section_descriptions.keys()), ) assert key not in _config_options_template, 'Cannot define option "%s" twice.' % key _config_options_template[key] = option return option
Remove a ConfigOption by key from the global store. Only for use in testing.
def _delete_option(key: str) -> None: """Remove a ConfigOption by key from the global store. Only for use in testing. """ try: del _config_options_template[key] assert ( _config_options is not None ), "_config_options should always be populated here." del _config_options[key] except Exception: # We don't care if the option already doesn't exist. pass
Are we in development mode. This option defaults to True if and only if Streamlit wasn't installed normally.
def _global_development_mode() -> bool: """Are we in development mode. This option defaults to True if and only if Streamlit wasn't installed normally. """ return ( not env_util.is_pex() and "site-packages" not in __file__ and "dist-packages" not in __file__ and "__pypackages__" not in __file__ )
Level of logging: 'error', 'warning', 'info', or 'debug'. Default: 'info'
def _logger_log_level() -> str: """Level of logging: 'error', 'warning', 'info', or 'debug'. Default: 'info' """ if get_option("global.logLevel"): return str(get_option("global.logLevel")) elif get_option("global.developmentMode"): return "debug" else: return "info"
String format for logging messages. If logger.datetimeFormat is set, logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See [Python's documentation](https://docs.python.org/2.6/library/logging.html#formatter-objects) for available attributes. Default: "%(asctime)s %(message)s"
def _logger_message_format() -> str: """String format for logging messages. If logger.datetimeFormat is set, logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See [Python's documentation](https://docs.python.org/2.6/library/logging.html#formatter-objects) for available attributes. Default: "%(asctime)s %(message)s" """ if get_option("global.developmentMode"): from streamlit.logger import DEFAULT_LOG_MESSAGE return DEFAULT_LOG_MESSAGE else: return "%(asctime)s %(message)s"
Symmetric key used to produce signed cookies. If deploying on multiple replicas, this should be set to the same value across all replicas to ensure they all share the same secret. Default: randomly generated secret key.
def _server_cookie_secret() -> str: """Symmetric key used to produce signed cookies. If deploying on multiple replicas, this should be set to the same value across all replicas to ensure they all share the same secret. Default: randomly generated secret key. """ return secrets.token_hex()
If false, will attempt to open a browser window on start. Default: false unless (1) we are on a Linux box where DISPLAY is unset, or (2) we are running in the Streamlit Atom plugin.
def _server_headless() -> bool: """If false, will attempt to open a browser window on start. Default: false unless (1) we are on a Linux box where DISPLAY is unset, or (2) we are running in the Streamlit Atom plugin. """ if env_util.IS_LINUX_OR_BSD and not os.getenv("DISPLAY"): # We're running in Linux and DISPLAY is unset return True if os.getenv("IS_RUNNING_IN_STREAMLIT_EDITOR_PLUGIN") is not None: # We're running within the Streamlit Atom plugin return True return False
The address where the server will listen for client and browser connections. Use this if you want to bind the server to a specific address. If set, the server will only be accessible from this address, and not from any aliases (like localhost). Default: (unset)
def _server_address() -> str | None: """The address where the server will listen for client and browser connections. Use this if you want to bind the server to a specific address. If set, the server will only be accessible from this address, and not from any aliases (like localhost). Default: (unset) """ return None
Port where users should point their browsers in order to connect to the app. This is used to: - Set the correct URL for XSRF protection purposes. - Show the URL on the terminal (part of `streamlit run`). - Open the browser automatically (part of `streamlit run`). This option is for advanced use cases. To change the port of your app, use `server.Port` instead. Don't use port 3000 which is reserved for internal development. Default: whatever value is set in server.port.
def _browser_server_port() -> int: """Port where users should point their browsers in order to connect to the app. This is used to: - Set the correct URL for XSRF protection purposes. - Show the URL on the terminal (part of `streamlit run`). - Open the browser automatically (part of `streamlit run`). This option is for advanced use cases. To change the port of your app, use `server.Port` instead. Don't use port 3000 which is reserved for internal development. Default: whatever value is set in server.port. """ return int(get_option("server.port"))
Indicate where (e.g. in which file) this option was defined. Parameters ---------- key : str The config option key of the form "section.optionName"
def get_where_defined(key: str) -> str: """Indicate where (e.g. in which file) this option was defined. Parameters ---------- key : str The config option key of the form "section.optionName" """ with _config_lock: config_options = get_config_options() if key not in config_options: raise RuntimeError('Config key "%s" not defined.' % key) return config_options[key].where_defined
Check if a given option has not been set by the user. Parameters ---------- option_name : str The option to check Returns ------- bool True if the option has not been set by the user.
def _is_unset(option_name: str) -> bool: """Check if a given option has not been set by the user. Parameters ---------- option_name : str The option to check Returns ------- bool True if the option has not been set by the user. """ return get_where_defined(option_name) == ConfigOption.DEFAULT_DEFINITION
Check if a given option was actually defined by the user. Parameters ---------- option_name : str The option to check Returns ------- bool True if the option has been set by the user.
def is_manually_set(option_name: str) -> bool: """Check if a given option was actually defined by the user. Parameters ---------- option_name : str The option to check Returns ------- bool True if the option has been set by the user. """ return get_where_defined(option_name) not in ( ConfigOption.DEFAULT_DEFINITION, ConfigOption.STREAMLIT_DEFINITION, )
Print all config options to the terminal.
def show_config() -> None: """Print all config options to the terminal.""" with _config_lock: assert ( _config_options is not None ), "_config_options should always be populated here." config_util.show_config(_section_descriptions, _config_options)
Set a config option by key / value pair. This function assumes that the _config_options dictionary has already been populated and thus should only be used within this file and by tests. Parameters ---------- key : str The key of the option, like "logger.level". value The value of the option. where_defined : str Tells the config system where this was set.
def _set_option(key: str, value: Any, where_defined: str) -> None: """Set a config option by key / value pair. This function assumes that the _config_options dictionary has already been populated and thus should only be used within this file and by tests. Parameters ---------- key : str The key of the option, like "logger.level". value The value of the option. where_defined : str Tells the config system where this was set. """ assert ( _config_options is not None ), "_config_options should always be populated here." if key not in _config_options: # Import logger locally to prevent circular references from streamlit.logger import get_logger LOGGER = get_logger(__name__) LOGGER.warning( f'"{key}" is not a valid config option. If you previously had this config option set, it may have been removed.' ) else: _config_options[key].set_value(value, where_defined)
Update the config system by parsing the environment variable. This should only be called from get_config_options.
def _update_config_with_sensitive_env_var(config_options: dict[str, ConfigOption]): """Update the config system by parsing the environment variable. This should only be called from get_config_options. """ for opt_name, opt_val in config_options.items(): if not opt_val.sensitive: continue env_var_value = os.environ.get(opt_val.env_var) if env_var_value is None: continue _set_option(opt_name, env_var_value, _DEFINED_BY_ENV_VAR)
Update the config system by parsing this string. This should only be called from get_config_options. Parameters ---------- raw_toml : str The TOML file to parse to update the config values. where_defined : str Tells the config system where this was set.
def _update_config_with_toml(raw_toml: str, where_defined: str) -> None: """Update the config system by parsing this string. This should only be called from get_config_options. Parameters ---------- raw_toml : str The TOML file to parse to update the config values. where_defined : str Tells the config system where this was set. """ import toml parsed_config_file = toml.loads(raw_toml) for section, options in parsed_config_file.items(): for name, value in options.items(): value = _maybe_read_env_variable(value) _set_option(f"{section}.{name}", value, where_defined)
If value is "env:foo", return value of environment variable "foo". If value is not in the shape above, returns the value right back. Parameters ---------- value : any The value to check Returns ------- any Either returns value right back, or the value of the environment variable.
def _maybe_read_env_variable(value: Any) -> Any: """If value is "env:foo", return value of environment variable "foo". If value is not in the shape above, returns the value right back. Parameters ---------- value : any The value to check Returns ------- any Either returns value right back, or the value of the environment variable. """ if isinstance(value, str) and value.startswith("env:"): var_name = value[len("env:") :] env_var = os.environ.get(var_name) if env_var is None: # Import logger locally to prevent circular references from streamlit.logger import get_logger LOGGER = get_logger(__name__) LOGGER.error("No environment variable called %s" % var_name) else: return _maybe_convert_to_number(env_var) return value
Convert v to int or float, or leave it as is.
def _maybe_convert_to_number(v: Any) -> Any: """Convert v to int or float, or leave it as is.""" try: return int(v) except Exception: pass try: return float(v) except Exception: pass return v
Create and return a dict mapping config option names to their values, returning a cached dict if possible. Config option values are sourced from the following locations. Values set in locations further down the list overwrite those set earlier. 1. default values defined in this file 2. the global `~/.streamlit/config.toml` file 3. per-project `$CWD/.streamlit/config.toml` files 4. environment variables such as `STREAMLIT_SERVER_PORT` 5. command line flags passed to `streamlit run` Parameters ---------- force_reparse : bool Force config files to be parsed so that we pick up any changes to them. options_from_flags : dict[str, any] or None Config options that we received via CLI flag. Returns ------- dict[str, ConfigOption] An ordered dict that maps config option names to their values.
def get_config_options( force_reparse=False, options_from_flags: dict[str, Any] | None = None ) -> dict[str, ConfigOption]: """Create and return a dict mapping config option names to their values, returning a cached dict if possible. Config option values are sourced from the following locations. Values set in locations further down the list overwrite those set earlier. 1. default values defined in this file 2. the global `~/.streamlit/config.toml` file 3. per-project `$CWD/.streamlit/config.toml` files 4. environment variables such as `STREAMLIT_SERVER_PORT` 5. command line flags passed to `streamlit run` Parameters ---------- force_reparse : bool Force config files to be parsed so that we pick up any changes to them. options_from_flags : dict[str, any] or None Config options that we received via CLI flag. Returns ------- dict[str, ConfigOption] An ordered dict that maps config option names to their values. """ global _config_options if not options_from_flags: options_from_flags = {} # Avoid grabbing the lock in the case where there's nothing for us to do. config_options = _config_options if config_options and not force_reparse: return config_options with _config_lock: # Short-circuit if config files were parsed while we were waiting on # the lock. if _config_options and not force_reparse: return _config_options old_options = _config_options _config_options = copy.deepcopy(_config_options_template) # Values set in files later in the CONFIG_FILENAMES list overwrite those # set earlier. for filename in CONFIG_FILENAMES: if not os.path.exists(filename): continue with open(filename, encoding="utf-8") as input: file_contents = input.read() _update_config_with_toml(file_contents, filename) _update_config_with_sensitive_env_var(_config_options) for opt_name, opt_val in options_from_flags.items(): _set_option(opt_name, opt_val, _DEFINED_BY_FLAG) if old_options and config_util.server_option_changed( old_options, _config_options ): # Import logger locally to prevent circular references. from streamlit.logger import get_logger LOGGER = get_logger(__name__) LOGGER.warning( "An update to the [server] config option section was detected." " To have these changes be reflected, please restart streamlit." ) _on_config_parsed.send() return _config_options
Wait for the config file to be parsed then call func. If the config file has already been parsed, just calls func immediately unless force_connect is set. Parameters ---------- func : Callable[[], None] A function to run on config parse. force_connect : bool Wait until the next config file parse to run func, even if config files have already been parsed. lock : bool If set, grab _config_lock before running func. Returns ------- Callable[[], bool] A function that the caller can use to deregister func.
def on_config_parsed( func: Callable[[], None], force_connect=False, lock=False ) -> Callable[[], bool]: """Wait for the config file to be parsed then call func. If the config file has already been parsed, just calls func immediately unless force_connect is set. Parameters ---------- func : Callable[[], None] A function to run on config parse. force_connect : bool Wait until the next config file parse to run func, even if config files have already been parsed. lock : bool If set, grab _config_lock before running func. Returns ------- Callable[[], bool] A function that the caller can use to deregister func. """ # We need to use the same receiver when we connect or disconnect on the # Signal. If we don't do this, then the registered receiver won't be released # leading to a memory leak because the Signal will keep a reference of the # callable argument. When the callable argument is an object method, then # the reference to that object won't be released. receiver = lambda _: func_with_lock() def disconnect(): return _on_config_parsed.disconnect(receiver) def func_with_lock(): if lock: with _config_lock: func() else: func() if force_connect or not _config_options: # weak=False so that we have control of when the on_config_parsed # callback is deregistered. _on_config_parsed.connect(receiver, weak=False) else: func_with_lock() return disconnect
Return True if and only if an option in the server section differs between old_options and new_options.
def server_option_changed( old_options: dict[str, ConfigOption], new_options: dict[str, ConfigOption] ) -> bool: """Return True if and only if an option in the server section differs between old_options and new_options. """ for opt_name in old_options.keys(): if not opt_name.startswith("server"): continue old_val = old_options[opt_name].value new_val = new_options[opt_name].value if old_val != new_val: return True return False
Print the given config sections/options to the terminal.
def show_config( section_descriptions: dict[str, str], config_options: dict[str, ConfigOption], ) -> None: """Print the given config sections/options to the terminal.""" out = [] out.append( _clean( """ # Below are all the sections and options you can have in ~/.streamlit/config.toml. """ ) ) def append_desc(text): out.append("# " + cli_util.style_for_cli(text, bold=True)) def append_comment(text): out.append("# " + cli_util.style_for_cli(text)) def append_section(text): out.append(cli_util.style_for_cli(text, bold=True, fg="green")) def append_setting(text): out.append(cli_util.style_for_cli(text, fg="green")) for section, _ in section_descriptions.items(): # We inject a fake config section used for unit tests that we exclude here as # its options are often missing required properties, which confuses the code # below. if section == "_test": continue section_options = { k: v for k, v in config_options.items() if v.section == section and v.visibility == "visible" and not v.is_expired() } # Only show config header if section is non-empty. if len(section_options) == 0: continue out.append("") append_section("[%s]" % section) out.append("") for key, option in section_options.items(): key = option.key.split(".")[1] description_paragraphs = _clean_paragraphs(option.description or "") last_paragraph_idx = len(description_paragraphs) - 1 for i, paragraph in enumerate(description_paragraphs): # Split paragraph into lines lines = paragraph.rstrip().split( "\n" ) # Remove trailing newline characters # If the first line is empty, remove it if lines and not lines[0].strip(): lines = lines[1:] # Choose function based on whether it's the first paragraph or not append_func = append_desc if i == 0 else append_comment # Add comment character to each line and add to out for line in lines: append_func(line.lstrip()) # # Add a line break after a paragraph only if it's not the last paragraph if i != last_paragraph_idx: out.append("") import toml toml_default = toml.dumps({"default": option.default_val}) toml_default = toml_default[10:].strip() if len(toml_default) > 0: # Ensure a line break before appending "Default" comment, if not already there if out[-1] != "": out.append("") append_comment("Default: %s" % toml_default) else: # Don't say "Default: (unset)" here because this branch applies # to complex config settings too. pass if option.deprecated: append_comment(cli_util.style_for_cli("DEPRECATED.", fg="yellow")) for line in _clean_paragraphs(option.deprecation_text): append_comment(line) append_comment( "This option will be removed on or after %s." % option.expiration_date ) option_is_manually_set = ( option.where_defined != ConfigOption.DEFAULT_DEFINITION ) if option_is_manually_set: append_comment("The value below was set in %s" % option.where_defined) toml_setting = toml.dumps({key: option.value}) if len(toml_setting) == 0: toml_setting = f"# {key} =\n" elif not option_is_manually_set: toml_setting = f"# {toml_setting}" append_setting(toml_setting) cli_util.print_to_cli("\n".join(out))
Replace sequences of multiple spaces with a single space, excluding newlines. Preserves leading and trailing spaces, and does not modify spaces in between lines.
def _clean(txt: str) -> str: """Replace sequences of multiple spaces with a single space, excluding newlines. Preserves leading and trailing spaces, and does not modify spaces in between lines. """ return re.sub(" +", " ", txt)
Split the text into paragraphs, preserve newlines within the paragraphs.
def _clean_paragraphs(txt: str) -> list[str]: """Split the text into paragraphs, preserve newlines within the paragraphs.""" # Strip both leading and trailing newlines. txt = txt.strip("\n") paragraphs = txt.split("\n\n") cleaned_paragraphs = [ "\n".join(_clean(line) for line in paragraph.split("\n")) for paragraph in paragraphs ] return cleaned_paragraphs
Return the top-level RunningCursor for the given container. This is the cursor that is used when user code calls something like `st.foo` (which uses the main container) or `st.sidebar.foo` (which uses the sidebar container).
def get_container_cursor( root_container: int | None, ) -> RunningCursor | None: """Return the top-level RunningCursor for the given container. This is the cursor that is used when user code calls something like `st.foo` (which uses the main container) or `st.sidebar.foo` (which uses the sidebar container). """ if root_container is None: return None ctx = get_script_run_ctx() if ctx is None: return None if root_container in ctx.cursors: return ctx.cursors[root_container] cursor = RunningCursor(root_container=root_container) ctx.cursors[root_container] = cursor return cursor
Print a warning if Streamlit is imported but not being run with `streamlit run`. The warning is printed only once, and is printed using the root logger.
def _maybe_print_use_warning() -> None: """Print a warning if Streamlit is imported but not being run with `streamlit run`. The warning is printed only once, and is printed using the root logger. """ global _use_warning_has_been_displayed if not _use_warning_has_been_displayed: _use_warning_has_been_displayed = True warning = cli_util.style_for_cli("Warning:", bold=True, fg="yellow") if env_util.is_repl(): logger.get_logger("root").warning( f"\n {warning} to view a Streamlit app on a browser, use Streamlit in a file and\n run it with the following command:\n\n streamlit run [FILE_NAME] [ARGUMENTS]" ) elif not runtime.exists() and config.get_option( "global.showWarningOnDirectExecution" ): script_name = sys.argv[0] logger.get_logger("root").warning( f"\n {warning} to view this Streamlit app on a browser, run it with the following\n command:\n\n streamlit run {script_name} [ARGUMENTS]" )
Get the last added DeltaGenerator of the stack in the current context. Returns None if the stack has only one element or is empty for whatever reason.
def get_last_dg_added_to_context_stack() -> DeltaGenerator | None: """Get the last added DeltaGenerator of the stack in the current context. Returns None if the stack has only one element or is empty for whatever reason. """ current_stack = dg_stack.get() # If set to "> 0" and thus return the only delta generator in the stack - which logically makes more sense -, some unit tests # fail. It looks like the reason is that they create their own main delta generator but do not populate the dg_stack correctly. However, to be on the safe-side, # we keep the logic but leave the comment as shared knowledge for whoever will look into this in the future. if len(current_stack) > 1: return current_stack[-1] return None
Return either value, or None, or dg. This is needed because Widgets have meaningful return values. This is unlike other elements, which always return None. Then we internally replace that None with a DeltaGenerator instance. However, sometimes a widget may want to return None, and in this case it should not be replaced by a DeltaGenerator. So we have a special NoValue object that gets replaced by None.
def _value_or_dg( value: type[NoValue] | Value | None, dg: DG, ) -> DG | Value | None: """Return either value, or None, or dg. This is needed because Widgets have meaningful return values. This is unlike other elements, which always return None. Then we internally replace that None with a DeltaGenerator instance. However, sometimes a widget may want to return None, and in this case it should not be replaced by a DeltaGenerator. So we have a special NoValue object that gets replaced by None. """ if value is NoValue: return None if value is None: return dg return cast(Value, value)
Enqueues a ForwardMsg proto to send to the app.
def _enqueue_message(msg: ForwardMsg_pb2.ForwardMsg) -> None: """Enqueues a ForwardMsg proto to send to the app.""" ctx = get_script_run_ctx() if ctx is None: raise NoSessionContext() if ctx.current_fragment_id and msg.WhichOneof("type") == "delta": msg.delta.fragment_id = ctx.current_fragment_id ctx.enqueue(msg)
Check if elements are nested in a forbidden way. Raises ------ StreamlitAPIException: throw if an invalid element nesting is detected.
def _check_nested_element_violation( dg: DeltaGenerator, block_type: str | None, ancestor_block_types: List[BlockType] ) -> None: """Check if elements are nested in a forbidden way. Raises ------ StreamlitAPIException: throw if an invalid element nesting is detected. """ if block_type == "column": num_of_parent_columns = dg._count_num_of_parent_columns(ancestor_block_types) if dg._root_container == RootContainer.SIDEBAR and num_of_parent_columns > 0: raise StreamlitAPIException( "Columns cannot be placed inside other columns in the sidebar. This is only possible in the main area of the app." ) if num_of_parent_columns > 1: raise StreamlitAPIException( "Columns can only be placed inside other columns up to one level of nesting." ) if block_type == "chat_message" and block_type in ancestor_block_types: raise StreamlitAPIException( "Chat messages cannot nested inside other chat messages." ) if block_type == "expandable" and block_type in ancestor_block_types: raise StreamlitAPIException( "Expanders may not be nested inside other expanders." ) if block_type == "popover" and block_type in ancestor_block_types: raise StreamlitAPIException("Popovers may not be nested inside other popovers.")
True if we should print deprecation warnings to the browser.
def _should_show_deprecation_warning_in_browser() -> bool: """True if we should print deprecation warnings to the browser.""" return bool(config.get_option("client.showErrorDetails"))
Show a deprecation warning message.
def show_deprecation_warning(message: str) -> None: """Show a deprecation warning message.""" if _should_show_deprecation_warning_in_browser(): streamlit.warning(message) # We always log deprecation warnings _LOGGER.warning(message)
Wrap an `st` function whose name has changed. Wrapped functions will run as normal, but will also show an st.warning saying that the old name will be removed after removal_date. (We generally set `removal_date` to 3 months from the deprecation date.) Parameters ---------- func The `st.` function whose name has changed. old_name The function's deprecated name within __init__.py. removal_date A date like "2020-01-01", indicating the last day we'll guarantee support for the deprecated name. extra_message An optional extra message to show in the deprecation warning. name_override An optional name to use in place of func.__name__.
def deprecate_func_name( func: TFunc, old_name: str, removal_date: str, extra_message: str | None = None, name_override: str | None = None, ) -> TFunc: """Wrap an `st` function whose name has changed. Wrapped functions will run as normal, but will also show an st.warning saying that the old name will be removed after removal_date. (We generally set `removal_date` to 3 months from the deprecation date.) Parameters ---------- func The `st.` function whose name has changed. old_name The function's deprecated name within __init__.py. removal_date A date like "2020-01-01", indicating the last day we'll guarantee support for the deprecated name. extra_message An optional extra message to show in the deprecation warning. name_override An optional name to use in place of func.__name__. """ @functools.wraps(func) def wrapped_func(*args, **kwargs): result = func(*args, **kwargs) show_deprecation_warning( make_deprecated_name_warning( old_name, name_override or func.__name__, removal_date, extra_message ) ) return result # Update the wrapped func's name & docstring so st.help does the right thing wrapped_func.__name__ = old_name wrapped_func.__doc__ = func.__doc__ return cast(TFunc, wrapped_func)
Wrap an `st` object whose name has changed. Wrapped objects will behave as normal, but will also show an st.warning saying that the old name will be removed after `removal_date`. (We generally set `removal_date` to 3 months from the deprecation date.) Parameters ---------- obj The `st.` object whose name has changed. old_name The object's deprecated name within __init__.py. new_name The object's new name within __init__.py. removal_date A date like "2020-01-01", indicating the last day we'll guarantee support for the deprecated name. include_st_prefix If False, does not prefix each of the object names in the deprecation essage with `st.*`. Defaults to True.
def deprecate_obj_name( obj: TObj, old_name: str, new_name: str, removal_date: str, include_st_prefix: bool = True, ) -> TObj: """Wrap an `st` object whose name has changed. Wrapped objects will behave as normal, but will also show an st.warning saying that the old name will be removed after `removal_date`. (We generally set `removal_date` to 3 months from the deprecation date.) Parameters ---------- obj The `st.` object whose name has changed. old_name The object's deprecated name within __init__.py. new_name The object's new name within __init__.py. removal_date A date like "2020-01-01", indicating the last day we'll guarantee support for the deprecated name. include_st_prefix If False, does not prefix each of the object names in the deprecation essage with `st.*`. Defaults to True. """ return _create_deprecated_obj_wrapper( obj, lambda: show_deprecation_warning( make_deprecated_name_warning( old_name, new_name, removal_date, include_st_prefix=include_st_prefix ) ), )
Create a wrapper for an object that has been deprecated. The first time one of the object's properties or functions is accessed, the given `show_warning` callback will be called.
def _create_deprecated_obj_wrapper(obj: TObj, show_warning: Callable[[], Any]) -> TObj: """Create a wrapper for an object that has been deprecated. The first time one of the object's properties or functions is accessed, the given `show_warning` callback will be called. """ has_shown_warning = False def maybe_show_warning() -> None: # Call `show_warning` if it hasn't already been called once. nonlocal has_shown_warning if not has_shown_warning: has_shown_warning = True show_warning() class Wrapper: def __init__(self): # Override all the Wrapped object's magic functions for name in Wrapper._get_magic_functions(obj.__class__): setattr( self.__class__, name, property(self._make_magic_function_proxy(name)), ) def __getattr__(self, attr): # We handle __getattr__ separately from our other magic # functions. The wrapped class may not actually implement it, # but we still need to implement it to call all its normal # functions. if attr in self.__dict__: return getattr(self, attr) maybe_show_warning() return getattr(obj, attr) @staticmethod def _get_magic_functions(cls) -> list[str]: # ignore the handful of magic functions we cannot override without # breaking the Wrapper. ignore = ("__class__", "__dict__", "__getattribute__", "__getattr__") return [ name for name in dir(cls) if name not in ignore and name.startswith("__") ] @staticmethod def _make_magic_function_proxy(name): def proxy(self, *args): maybe_show_warning() return getattr(obj, name) return proxy return cast(TObj, Wrapper())
Use in a `with` block to draw some code on the app, then execute it. Parameters ---------- code_location : "above" or "below" Whether to show the echoed code before or after the results of the executed code block. Example ------- >>> import streamlit as st >>> >>> with st.echo(): >>> st.write('This code will be printed')
def echo(code_location="above"): """Use in a `with` block to draw some code on the app, then execute it. Parameters ---------- code_location : "above" or "below" Whether to show the echoed code before or after the results of the executed code block. Example ------- >>> import streamlit as st >>> >>> with st.echo(): >>> st.write('This code will be printed') """ from streamlit import code, empty, source_util, warning if code_location == "below": show_code = code show_warning = warning else: placeholder = empty() show_code = placeholder.code show_warning = placeholder.warning try: # Get stack frame *before* running the echoed code. The frame's # line number will point to the `st.echo` statement we're running. frame = traceback.extract_stack()[-3] filename, start_line = frame.filename, frame.lineno or 0 # Read the file containing the source code of the echoed statement. with source_util.open_python_file(filename) as source_file: source_lines = source_file.readlines() # Use ast to parse the Python file and find the code block to display root_node = ast.parse("".join(source_lines)) line_to_node_map: dict[int, Any] = {} def collect_body_statements(node: ast.AST) -> None: if not hasattr(node, "body"): return for child in ast.iter_child_nodes(node): # If child doesn't have "lineno", it is not something we could display if hasattr(child, "lineno"): line_to_node_map[child.lineno] = child collect_body_statements(child) collect_body_statements(root_node) # In AST module the lineno (line numbers) are 1-indexed, # so we decrease it by 1 to lookup in source lines list echo_block_start_line = line_to_node_map[start_line].body[0].lineno - 1 echo_block_end_line = line_to_node_map[start_line].end_lineno lines_to_display = source_lines[echo_block_start_line:echo_block_end_line] code_string = textwrap.dedent("".join(lines_to_display)) # Run the echoed code... yield # And draw the code string to the app! show_code(code_string, "python") except FileNotFoundError as err: show_warning("Unable to display code. %s" % err)
Return the indent of the first non-empty line in the list. If all lines are empty, return 0.
def _get_initial_indent(lines: Iterable[str]) -> int: """Return the indent of the first non-empty line in the list. If all lines are empty, return 0. """ for line in lines: indent = _get_indent(line) if indent is not None: return indent return 0
Get the number of whitespaces at the beginning of the given line. If the line is empty, or if it contains just whitespace and a newline, return None.
def _get_indent(line: str) -> int | None: """Get the number of whitespaces at the beginning of the given line. If the line is empty, or if it contains just whitespace and a newline, return None. """ if _EMPTY_LINE_RE.match(line) is not None: return None match = _SPACES_RE.match(line) return match.end() if match is not None else 0
Return if streamlit running in pex. Pex modifies sys.path so the pex file is the first path and that's how we determine we're running in the pex file.
def is_pex() -> bool: """Return if streamlit running in pex. Pex modifies sys.path so the pex file is the first path and that's how we determine we're running in the pex file. """ if re.match(r".*pex$", sys.path[0]): return True return False
Return True if running in the Python REPL.
def is_repl() -> bool: """Return True if running in the Python REPL.""" import inspect root_frame = inspect.stack()[-1] filename = root_frame[1] # 1 is the filename field in this tuple. if filename.endswith(os.path.join("bin", "ipython")): return True # <stdin> is what the basic Python REPL calls the root frame's # filename, and <string> is what iPython sometimes calls it. if filename in ("<stdin>", "<string>"): return True return False
Check if executable is in OS path.
def is_executable_in_path(name: str) -> bool: """Check if executable is in OS path.""" from shutil import which return which(name) is not None