A
A
Alexander Kurakin2017-07-26 11:45:50
Python
Alexander Kurakin, 2017-07-26 11:45:50

How to "hash" function code in Python?

I'm doing a (cycling) cache of function calls (memoizing) in Python 3. One of the subtasks is hashing functions (meaning function code).
It is necessary to hash ordinary functions:

def f(a):
    return a > 0

As well as derivatives
another_func = conjunction(f, g)
obtained using
import functools
def conjunction(*funcs):
    def conjunct(*args, **kwargs):
        return functools.reduce(lambda total_result, next_function: total_result and next_function(*args, **kwargs), funcs, True)
    return conjunct

I decided to use f.__code__.co_code, but the functions called in the function are not taken into account. There is also a suspicion (not confirmed) that even if the function is unchanged, it changes f.__code__.co_code(perhaps when clearing the internal Python cache).
Tell me something, please? Maybe there is a library for this (I didn't find it)? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-07-26
@longclaps

I would not bother sculpting the signature of the generated function, directly as a line. You have one and only factory - conjunction, there is, let's say, a set of primary functions - a (...), b (...) and c (...), well, push them into the "a", "b" docstring , "c", and in conjunction assign a concatenation to the docstring. And in debugging there will be something to read. Yes, and for several different factories you will come up with.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question