Skip to content

Improve function cache error message  #992

@olejorgenb

Description

@olejorgenb

Problem

app.py:

import datetime
import streamlit as st

def bar():
    return datetime.strptime("12", "%H")

@st.cache
def foo():
    return bar()

def main():
    foo()

if __name__ == '__main__':
    main()

streamlit run app.py

The error message in the browser:

Streamlit failed to hash an object of type <class 'function'>.

...

TypeError: object supporting the buffer API required
Traceback:

  File "/home/ole/.miniconda3/envs/streamlit-pg/lib/python3.7/site-packages/streamlit/ScriptRunner.py", line 324, in _run_script
    exec(code, module.__dict__)
  File "/home/ole/src/streamlit_test/app.py", line 15, in <module>
    main()
  File "/home/ole/src/streamlit_test/app.py", line 12, in main
    foo()
  File "/home/ole/.miniconda3/envs/streamlit-pg/lib/python3.7/site-packages/streamlit/caching.py", line 463, in wrapped_func
    return get_or_set_cache()
  File "/home/ole/.miniconda3/envs/streamlit-pg/lib/python3.7/site-packages/streamlit/caching.py", line 432, in get_or_set_cache
    code_hasher.update(func)
  File "/home/ole/.miniconda3/envs/streamlit-pg/lib/python3.7/site-packages/streamlit/hashing.py", line 211, in update
    self._update(self.hasher, obj, context)
  File "/home/ole/.miniconda3/envs/streamlit-pg/lib/python3.7/site-packages/streamlit/hashing.py", line 243, in _update
    hasher.update(b)

To me it's hard to guess from the reported error that the cause is a "compile" error inside bar

Wrapping the content of _code_to_bytes in hashing.py in a try catch reveals the real error - in this case very helpful:

AttributeError: module 'datetime' has no attribute 'strptime'

Solution

Somehow collect the root-cause exception and display that in the browser. Bonus if more info is collect, like the associated function name (in case of function hashing)

Metadata

Metadata

Assignees

Labels

feature:cacheRelated to `st.cache_data` and `st.cache_resource`type:enhancementRequests for feature enhancements or new features

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions