Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that a python function generates its output based only on its input?

To generate an output a function usually uses only values of its arguments. However, there are also cases in which function, to generate its output, reads something from a file system or from a database or from the web. I would like to have a simple and reliable way to ensure that something like that does not happen.

One way that I see is to create a white-list of python libraries that can be used to read from file system, database or web. But if it is the way to go, where can I get this (potentially huge) list. Moreover, I do not want to disable the whole library just because it can be used to read from the file system. For example I want users to be able to use pandas library (to store and manipulate tabular data). I just do not want them to be able to use this library to read data from the file system.

Is there a solution for this problem?

like image 882
Roman Avatar asked Oct 10 '14 15:10

Roman


People also ask

How can I use a function output as an input of another function in Python?

Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.

What is a pure function Python?

A pure function is a function whose output value follows solely from its input values, without any observable side effects. In functional programming, a program consists entirely of evaluation of pure functions. Computation proceeds by nested or composed function calls, without changes to state or mutable data.

How do you get output in Python?

In Python 3. x, you can output without a newline by passing end="" to the print function or by using the method write: import sys print("Hello", end="") sys. stdout.


1 Answers

The answer to this is no. What you are looking for is a function that tests for functional purity. But, as demonstrated in this code, there's no way to guarantee that no side effects are actually being called.

class Foo(object):
    def __init__(self, x):
        self.x = x
    def __add__(self, y):
        print("HAHAHA evil side effects here...")
        # proceed to read a file and do stuff
        return self

# this looks pure...
def f(x): return x + 1

# but really...
>>> f(Foo(1))
HAHAHA evil side effects here...

Because of the comprehensive way objects can redefine their behavior (field access, calling, operator overloading etc.), you can always pass an input that makes a pure function impure. Therefore the only pure functions are those that literally do nothing with their arguments... a class of functions that is generally less useful.

Of course, if you can specify other restrictions, this becomes easier.

like image 71
PythonNut Avatar answered Oct 05 '22 14:10

PythonNut