Search code examples
pythonfunctional-programmingmutability

Calling child process and functional programming


Is it possible to avoid side effects and still create a child process? Example:

from subprocess import call

def ls(directory):
    return call("ls %s" % directory, shell=True)

If isn't possible, how functional languages make such operations?

Thanks.


Solution

  • In functional languages creating child processes and doing anything like the one given is not a pure function it has side effects

    In functional languages there are impure functions aswell but it would try to minimise code in impure functions and make the fact that a function is impure explicit. You may read about IO monads

    Considering Haskell being the most functional language for example,it explicitly says it has side effects on its signature/declaration for createProcess function

    createProcess :: CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
    

    The IO explicitly says it has side effects

    If you just need to avoid the out put you may do it like this

    import os
    import subprocess
    
    FNULL = open(os.devnull, 'w')
    
    def ls(directory):
        return subprocess.call(['ls',directory], stdout=FNULL, stderr=FNULL)