Thursday, March 3, 2011

anonymous unbound functions in python

I would like to do something like the following:

def add(a, b):
    #some code

def subtract(a, b):
    #some code

operations = [add, subtract]
operations[0]( 5,3)
operations[1](5,3)

In python, is it possible to assign something like a function pointer?

From stackoverflow
  • Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.

    Phil H : "Python is executable pseudocode"
  • Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value.

    You can use this to implement a Strategy pattern, for example:

    def the_simple_way(a, b):
        # blah blah
    
    def the_complicated_way(a, b):
        # blah blah
    
    def foo(way):
        if way == 'complicated':
            doit = the_complicated_way
        else:
            doit = the_simple_way
    
        doit(a, b)
    

    Or a lookup table:

    def do_add(a, b):
        return a+b
    
    def do_sub(a, b):
        return a-b
    
    handlers = {
        'add': do_add,
        'sub': do_sub,
    }
    
    print handlers[op](a, b)
    

    You can even grab a method bound to an object:

    o = MyObject()
    f = o.method
    f(1, 2) # same as o.method(1, 2)
    
  • Just a quick note that most Python operators already have an equivalent function in the operator module.

0 comments:

Post a Comment