Display only object attributes not repr or doc

Can I display only attributes of an object? If I use st.write it displays something like repr, then the docstring and then the table of the attributes. E.g., this

@dataclasses.dataclass
class Foo:
    a: int
    b: float
    c: list

st.write(Foo(1, 2.3, [1, 2, 3, 5, 6]))

is displayed like this:

I like the table of attributes, how it displays type and value of each attribute. But I don’t want to show the repr and doc part. I find it rather distracting. Is there a way to suppress these?

Ideally there would be function like st.write_object, where one could configure what should be displayed…

Streamlit doesn’t have a built-in function to hide the repr and docstring when displaying an object. However, you can achieve the behavior you’re looking for by manually displaying the attributes of the object in a way that mimics how Streamlit shows the table of attributes.

Here’s one way to do it using a dictionary comprehension that extracts the attributes and types from a dataclass:

import streamlit as st
import dataclasses

@dataclasses.dataclass
class Foo:
    a: int
    b: float
    c: list

# Create an instance of the Foo class
foo_instance = Foo(1, 2.3, [1, 2, 3, 5, 6])

# Extract the attributes and their types and values
attributes = {field.name: (type(getattr(foo_instance, field.name)).__name__, getattr(foo_instance, field.name)) for field in dataclasses.fields(foo_instance)}

# Display the attributes in a table format
st.write("### Object Attributes")
st.table(attributes)

Explanation:

  • dataclasses.fields(): This retrieves all the fields in the dataclass.
  • getattr(): This is used to get the value of each attribute dynamically.
  • type().__name__: This extracts the name of the type of each attribute.
  • st.table(): Displays the attributes as a table, showing both the type and the value of each attribute.

This approach will display only the attributes, without showing the repr or docstring, and it gives you full control over what is displayed.

Hello Nico,

thanks for the proposal, I have already implemented something similar…, but it does not look that nice. I just prefer how the attributes at types are formatted (and colored) when printing the whole object using st.write, this would be harder to replicate. Thats why I asked if the functionality that already is in the Streamlit could be used to display the attributes only.

Maybe I shall create a feature request on the Github? That functionality is already implemented, we just need to make it configurable (so that is omits the repr or doc).