10

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?

5
  • 1
    Try actually executing that code in the interactive environment and see what happens. Commented Nov 21, 2008 at 1:27
  • I'm tempted to delete the silly [function-pointer] and [anonymous-methods] tags because they don't makes sense in Python. But then, this kind of question shows that Python lacks those complexities. Commented Nov 21, 2008 at 2:22
  • 2
    you're in luck, my friend, but they're neither anonymous nor unbound Commented Nov 21, 2008 at 2:42
  • I think by "unbound functions" he meant "functions, not methods". Commented Nov 21, 2008 at 8:26
  • No, "unbound functions" is a hair-splitting in C++ and "prothon" to explain functions that are not (yet) bound to a class, but could be. And Java folks have to give functions fancy-sounding names. Commented Nov 21, 2008 at 11:30

3 Answers 3

29

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

Sign up to request clarification or add additional context in comments.

Comments

9

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)

2 Comments

If they are not called "function pointers", what do you call them? Just function as in my mind, a function is either the definition or its call that includes the parentheses. But I am no expert.
If you do this: def foo(): ...; bar = foo then foo and bar are both names referring to a function. There is no difference between them. So if foo is a function, then why isn't bar a function?
1

Just a quick note that most Python operators already have an equivalent function in the operator module.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.