UnhashableTypeError: Cannot hash object of type _thread.lock, found in the arguments of get_price()

Hi, I’m trying to build a web-app to monitor my financial portfolio and I get the last update on the stock prices using a custom function (get_price()).
Since I want to plot a chart that can vary without re-run again everything just changing the security name in the sidebar I need to cache (or at least I think I need) the function to retrieve the prices and in doing it I get this error.
UnhashableTypeError : Cannot hash object of type _thread.lock , found in the arguments of get_price()

The function structure:

@st.cache(suppress_st_warning=False,allow_output_mutation=True) # to cache the function and not re-execute it again
def get_price(driver: webdriver.chrome.webdriver.WebDriver, source: str, ticker: str):
    """
    Retrieve the last prices from a specified web-source
    :param driver: the Google Chrome webdriver object to perform the search
    :param source: the web-source of the price (supported are: Investing.com, Borsa Italiana, Yahoo finance)
    :param tickers: a list of the tickers of the instruments to monitor
    :return last_price: the updated price of the security
    """

How can I overcome the error?

The entire error is:


UnhashableTypeError: Cannot hash object of type _thread.lock, found in the arguments of get_price().

While caching the arguments of get_price(), Streamlit encountered an object of type _thread.lock, which it does not know how to hash.

To address this, please try helping Streamlit understand how to hash that type by passing the hash_funcs argument into @st.cache. For example:


@st.cache(hash_funcs={_thread.lock: my_hash_func})
def my_func(...):
    ...
If you don't know where the object of type _thread.lock is coming from, try looking at the hash chain below for an object that you do recognize, then pass that to hash_funcs instead:


Object of type _thread.lock: <unlocked _thread.lock object at 0x000002A9E15A5E10>
Object of type builtins.tuple: ('_waitpid_lock', <unlocked _thread.lock object at 0x000002A9E15A5E10>)
Object of type builtins.dict: {'_waitpid_lock': <unlocked _thread.lock object at 0x000002A9E15A5E10>, '_input': None, '_communication_started': False, 'args': ['C:\\Users\\leoac\\OneDrive\\Desktop\\Coding\\Python apps\\Investement display\\chromedriver.exe', '--port=51569'], 'stdin': <_io.BufferedWriter name=6>, 'stdout': None, 'stderr': None, 'pid': 6528, 'returncode': None, 'encoding': None, 'errors': None, '_devnull': 5, 'text_mode': None, '_sigint_wait_secs': 0.25, '_closed_child_pipe_fds': True, '_child_created': True, '_handle': Handle(2968)}
Object of type subprocess.Popen: <Popen: returncode: None args: ['C:\\Users\\leoac\\OneDrive\\Desktop\\Coding...>
Object of type builtins.tuple: ('process', <Popen: returncode: None args: ['C:\\Users\\leoac\\OneDrive\\Desktop\\Coding...>)
Object of type builtins.dict: {'service_args': [], 'path': 'C:\\Users\\leoac\\OneDrive\\Desktop\\Coding\\Python apps\\Investement display\\chromedriver.exe', 'port': 51569, 'start_error_message': 'Please see https://sites.google.com/a/chromium.org/chromedriver/home', 'log_file': -3, 'env': environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\leoac\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DELL-INSPIRON', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\leoac', 'LOCALAPPDATA': 'C:\\Users\\leoac\\AppData\\Local', 'LOGONSERVER': '\\\\DELL-INSPIRON', 'NUMBER_OF_PROCESSORS': '8', 'ONEDRIVE': 'C:\\Users\\leoac\\OneDrive - Università Politecnica delle Marche', 'ONEDRIVECOMMERCIAL': 'C:\\Users\\leoac\\OneDrive - Università Politecnica delle Marche', 'ONEDRIVECONSUMER': 'C:\\Users\\leoac\\OneDrive', 'OS': 'Windows_NT', 'PATH': 'C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files\\dotnet\\;C:\\Program Files\\Git\\cmd;C:\\Users\\leoac\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\;C:\\Users\\leoac\\AppData\\Local\\Programs\\Python\\Python39\\;C:\\Users\\leoac\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\leoac\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\Program Files\\gretl;C:\\Users\\leoac\\AppData\\Local\\GitHubDesktop\\bin', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 140 Stepping 1, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '8c01', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'RTOOLS42_HOME': 'C:\\rtools42', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\WINDOWS', 'TEMP': 'C:\\Users\\leoac\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\leoac\\AppData\\Local\\Temp', 'USERDOMAIN': 'DELL-INSPIRON', 'USERDOMAIN_ROAMINGPROFILE': 'DELL-INSPIRON', 'USERNAME': 'leoac', 'USERPROFILE': 'C:\\Users\\leoac', 'WINDIR': 'C:\\WINDOWS', 'ZES_ENABLE_SYSMAN': '1', 'MAPBOX_API_KEY': ''}), 'process': <Popen: returncode: None args: ['C:\\Users\\leoac\\OneDrive\\Desktop\\Coding...>}
Object of type selenium.webdriver.chrome.service.Service: <selenium.webdriver.chrome.service.Service object at 0x000002A9DB8E80A0>
Object of type builtins.tuple: ('service', <selenium.webdriver.chrome.service.Service object at 0x000002A9DB8E80A0>)
Object of type builtins.dict: {'service': <selenium.webdriver.chrome.service.Service object at 0x000002A9DB8E80A0>, 'command_executor': <selenium.webdriver.chrome.remote_connection.ChromeRemoteConnection object at 0x000002A9E15A5A90>, '_is_remote': False, 'session_id': '58035f35d399e9a64210480dd0cd3e9d', 'capabilities': {'acceptInsecureCerts': False, 'browserName': 'chrome', 'browserVersion': '109.0.5414.76', 'chrome': {'chromedriverVersion': '109.0.5414.74 (e7c5703604daa9cc128ccf5a5d3e993513758913-refs/branch-heads/5414@{#1172})', 'userDataDir': 'C:\\Users\\leoac\\AppData\\Local\\Temp\\scoped_dir6528_2008914870'}, 'goog:chromeOptions': {'debuggerAddress': 'localhost:51577'}, 'networkConnectionEnabled': False, 'pageLoadStrategy': 'normal', 'platformName': 'windows', 'proxy': {}, 'setWindowRect': True, 'strictFileInteractability': False, 'timeouts': {'implicit': 0, 'pageLoad': 300000, 'script': 30000}, 'unhandledPromptBehavior': 'dismiss and notify', 'webauthn:extension:credBlob': True, 'webauthn:extension:largeBlob': True, 'webauthn:virtualAuthenticators': True}, 'error_handler': <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x000002A9E15A5C40>, 'w3c': True, '_switch_to': <selenium.webdriver.remote.switch_to.SwitchTo object at 0x000002A9E13FD7F0>, '_mobile': <selenium.webdriver.remote.mobile.Mobile object at 0x000002A9E15A5BE0>, '_file_detector': <selenium.webdriver.remote.file_detector.LocalFileDetector object at 0x000002A9E15DA790>}
Object of type selenium.webdriver.chrome.webdriver.WebDriver: <selenium.webdriver.chrome.webdriver.WebDriver (session="58035f35d399e9a64210480dd0cd3e9d")>
Object of type builtins.tuple: (<selenium.webdriver.chrome.webdriver.WebDriver (session="58035f35d399e9a64210480dd0cd3e9d")>, 'yahoo finance', 'BTC-EUR')
Please see the hash_funcs [documentation] (https://docs.streamlit.io/library/advanced-features/caching#the-hash_funcs-parameter) for more details.

Traceback:
File "C:\Users\leoac\OneDrive\Desktop\Coding\Python apps\Investement display\portfolio_display.py", line 136, in <module>
    prices = [get_price(g,securities.data_source[securities.ticker == t].values[0],t) for t in securities.ticker.values]
File "C:\Users\leoac\OneDrive\Desktop\Coding\Python apps\Investement display\portfolio_display.py", line 136, in <listcomp>
    prices = [get_price(g,securities.data_source[securities.ticker == t].values[0],t) for t in securities.ticker.values]
File "C:\Users\leoac\AppData\Local\Programs\Python\Python39\lib\copyreg.py", line 70, in _reduce_ex
    raise TypeError(f"cannot pickle {cls.__name__!r} object")
Made with Streamlit

Two suggestions:

  1. Use st.experimental_memo - Streamlit Docs instead of the soon-to-be-deprecated st.cache
  2. Don’t pass in the driver unless you have to, as that’s a bit of a weird input to cache. It may work with experimental_memo, but if it doesn’t I would try having the driver be a global object (at least relative to the function) so that you don’t have to pass it in.

Thanks!
It solved the issue, great!

1 Like