holoviz / panel

Panel: The powerful data exploration & web app framework for Python
https://panel.holoviz.org
BSD 3-Clause "New" or "Revised" License
4.8k stars 519 forks source link

pn.cache fails with hashable object #7478

Closed MarcSkovMadsen closed 1 week ago

MarcSkovMadsen commented 1 week ago

panel==1.5.3

I would expect pn.cache hashing mechanism to use objects __hash__ method if available:

import panel as pn

class DatabaseConnector():
    def __init__(self, url, view_sql):
        self.url = url
        self.view_sql = view_sql

    def __hash__(self):
        text = self.url, self.view_sql
        return hash(text)

@pn.cache
def my_func(val: DatabaseConnector):
    return val

my_func(DatabaseConnector("sqlite:///foo.db", "SELECT * FROM table_name"))

But it seems not

  File "/home/jovyan/repos/private/panel-graphic-walker/.venv/lib/python3.11/site-packages/panel/io/cache.py", line 235, in _generate_hash
    hash_value = _generate_hash_inner(obj)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jovyan/repos/private/panel-graphic-walker/.venv/lib/python3.11/site-packages/panel/io/cache.py", line 212, in _generate_hash_inner
    raise ValueError(
ValueError: User hash function <function _container_hash at 0x7f4a52ee31a0> failed for input (<__main__.DatabaseConnector object at 0x7f4aa5e75d10>,) with following error: ValueError("Could not hash object of type function").

As a workaround I need to add the hash method to panel.io.cache._hash_funcs.