Python: strategies for memorizing functions with function arguments briefly?

I wrote a small class to constantly remember some expensive functions that perform various statistical analyzes of random networks.

These are all pure functions; All data is immutable. However, some functions accept functions as arguments.

Creating keys based on these arguments is a small problem, because the equivalent of the identifier of the function object in the function of the Python function object is not stored between sessions, even if the implementation of the function does not change.

I am now using this name, using the name of the function as a string, but there is a problem when you start thinking about changing the implementation of the function or anonymous functions, etc. But I'm probably not the first to worry about such things.

Does anyone have any strategies for persistent memoizing functions with function arguments in Python?

+5
source share
2 answers

See how to use this function as a function identifier

[getattr(func.__code__,s) 
 for s in ['co_argcount', 'co_cellvars', 'co_code', 'co_consts', 
           'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars',
           'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize',
           'co_varnames']
]

which should correctly handle the implementation change in any way ...

+2
source

One option is to use marshal.dumps(function.func_code)

It gives a string representation for the function code. This should handle changing implementations and anonymous functions.

+3
source

All Articles