Problem decorating Python stored procedure handler with @functools.cache

24 Views Asked by At

I am building a Python stored procedure that will execute a lengthy process and return a result. To improve performance, the handler code will be decorated with functools.cache to cache results. The following code is a minimal example that demonstrates the problem:

create or replace function get_key(which varchar) returns varchar
language python runtime_version = '3.11'
packages = ('snowflake-snowpark-python')
handler = 'get_key'
AS $$
import functools

@functools.cache
def get_key(which):
  if which == 'PN':
    return 'toomanysecrets'
  else:
    return ''
$$;

select get_key('PN');

Error is

Python Interpreter Error: AttributeError: 'functools._lru_cache_wrapper' object has no attribute '__code__' in function GET_KEY with handler get_key

1

There are 1 best solutions below

0
Dave Welden On

OK, turns out to have a simple solution: I created an additional function that is wrapped with the cache decorator, and changed the handle function to call it:

create or replace function get_key(which varchar) returns varchar
language python runtime_version = '3.11'
packages = ('snowflake-snowpark-python')
handler = 'main'
AS $$
import functools

@functools.cache
def get_key(which):
  if which == 'PN':
    return 'toomanysecrets'
  else:
    return ''

def main(which):
  return get_key(which)
$$;