Is it possible to find out if two python functions are functional?

Let's say I have two functions python f and g :

 def f(x): y = x**2 + 1 return y def g(x): a = x**2 b = a + 1 return b 

These two functions are explicitly functionally equivalent (both return x**2 + 1 ).

My definition of functionally equivalent is as follows:

If two functions f and g always produce the same output with the same input, then f and g are functionally equivalent.

Further, suppose that global variables are not involved in f and g .

Is it possible to automatically detect (without human control) if the python f and g functions are functionally equivalent?

+5
source share
2 answers

Rhys Theorem , no. If you could do this, you could solve the problem. (This is true even if f and g always guaranteed to stop.)

+12
source

If the functions are in fact one and the same object, you can just do f == g and see whether they are the same object.

Secondly, if functions have the same bytecode ( f.func_code.co_code ), then they are equivalent.

Equivalent (but probably more portable), you can use dis.dis to get the same information. Please note that this will be subject to false negatives, as in this case.

I understand that dill will be better, and will allow you to get the function text. Using this information, you can use ast to analyze text and perform similar analyzes to optimize compilers to decide whether code can be "optimized" into the same syntax tree. Again, there will be functionally equivalent functions that cannot simply be reduced to the same ast.

So, yes, for some pairs of functionally equivalent functions this detection is possible, but there will always be false negatives.

+2
source

Source: https://habr.com/ru/post/1247900/


All Articles