0

Is there a reasonably natural way of converting python function to standalone scripts? Something like:

def f(): 
    # some long and involved computation

script = function_to_script(f) # now script is some sort of closure, 
                               # which can be run in a separate process
                               # or even shipped over the network to a 
                               # different host

and NOT like:

script = open("script.py", "wt")
script.write("#!/usr/bin/env python")
...
Timur
  • 23
  • 2
  • Are you looking for something like this? http://pythonhosted.org/Pyro4/ – Robert Harvey Mar 27 '13 at 22:43
  • Not really - as I understand Pyro is a library for communication over the network. I need something to encapsulate computation. – Timur Mar 28 '13 at 02:52
  • Pyro is a remoting library. It allows functions to be called cross-process or cross-host. Functions already encapsulate computation, and Pyro would allow you to call those functions somewhere else, so if it's not that, then what are you trying to accomplish? Are you looking for a Eval function? – Robert Harvey Mar 28 '13 at 03:03

1 Answers1

2

You can turn any "object" into a function by defining the __call__ method on it (see here.) Hence, if you want to compartmentalize some state with the computations, as long as what you've provided from the very top to the bottom of a class can be pickled, then that object can be pickled.

class MyPickledFunction(object):
    def __init__(self, *state):
        self.__state = state

    def __call__(self, *args, **kwargs):
        #stuff in here

That's the easy cheater way. Why pickling? Anything that can be pickled can be sent to another process without fear. You're forming a "poor man's closure" by using an object like this.

(There's a nice post about the "marshal" library here on SO if you want to truly pickle a function.)

Community
  • 1
  • 1
wheaties
  • 35,646
  • 15
  • 94
  • 131