Invoking functions using a function pointer approach I re-used this answer from this StackOverflow answer to simulate a function pointer approach available in high-level languages like C.

While using this approach in Python, the dictionary I am defining to map the functions needs to be defined after all the functions are defined before. It makes the dictionary definition to be the last segment of the code, which doesn't look neat.

Is there a way like in C to export all the functions beforehand, so that I can define the mapping dictionary in the beginning? (See examples below). Or what would be the most pythonic approach to do this?

Below is my sample snippet of the code using the approach.

File-1 - a1.py

#!/usr/bin/env python

from a2 import *

def arithmeticOps():
    doOps('add',6,1)
    doOps('mul',6,4)

if __name__ == '__main__':
    arithmeticOps()


and File-2 - a2.py

#!/usr/bin/env python

def doOps(op, arg1, arg2):
    arithDict[op](arg1,arg2)

def doAdd(arg1, arg2):
    print "Sum =",arg1 + arg2

def doProd(arg1, arg2):
    print "Prod =",arg1 * arg2

arithDict = {
    'add': doAdd,
    'mul': doProd
}


I am able to run this code peacefully in Python 2.7, and it gives me the result I need.

# python a1.py 
Sum = 7
Prod = 24


I agree the built-in functions for addition (or) product could be used here, but the problem is for a bigger scale when I have custom functions in place.
You don't have to define your own functions for these arithmetic operations. These functions already exist in the operator module.

from operator import add, mul

operations = {
    'add': add,
    'mul': mul
}

In Python snake-case is preferred over camelCase for variable names.
Don't use import * imports. Import only the items you need. import * based imports can be helpful in shell for debugging and you may sometimes see them in a package's __init__.py to help define a clean public API.





  Is there a way like in C to export all the functions before-hand, so
  that I can define the mapping dictionary in the beginning (See
  examples below). Or what would be the most pythonic approach to do
  this?


There's no way to import only functions. The pythonic way is to import only the functions you need not everything.


  It makes the dictionary definition to be the last segment of the code
  which doesn't look neat.


The dictionary approach is recommended in Python as there's no switch statement in Python and it's better than a bunch of if-elif-else. You could also create the dict in a1.py based on the imported functions. Though I don't find its definition in a2.py okay.

Another option can be to fetch the functions from a2 module object itself if they can be re-named add, mul etc. This way you won't need a dict.

import a2

def arithmeticOps():
    getattr(a2, 'add')(6, 1)
    getattr(a2, 'mul')(6, 4)