Created
April 19, 2022 17:45
-
-
Save asehmi/086e267a1f0e8a9b39317b859fb5b82e to your computer and use it in GitHub Desktop.
Optional echo code for Streamlit
This file contains hidden or 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
import streamlit as st | |
import traceback | |
# https://gist.github.com/tvst/6e62360a712ed0595e7a0749127fba58 | |
class opt_echo: | |
"""Replacement for st.echo that includes a checkbox saying "show code". | |
Usage | |
----- | |
>>> with opt_echo(): | |
... a = 1337 | |
""" | |
def __init__(self): | |
self.checkbox = st.checkbox("show code") | |
# This is a mega-hack! | |
# And it's also not thread-safe. Don't use this if you have threaded | |
# code that depends on traceback.extract_stack | |
self.orig_extract_stack = traceback.extract_stack | |
if self.checkbox: | |
traceback.extract_stack = lambda: self.orig_extract_stack()[:-2] | |
self.echo = st.echo() | |
def __enter__(self): | |
if self.checkbox: | |
return self.echo.__enter__() | |
def __exit__(self, type, value, traceback): | |
if self.checkbox: | |
self.echo.__exit__(type, value, traceback) | |
# For some reason I need to import this again. | |
import traceback | |
traceback.extract_stack = self.orig_extract_stack | |
with opt_echo(): | |
st.write("hello.") |
Author
asehmi
commented
Apr 19, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment