Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substitute of function pointers in python

Tags:

python

I have worked in low level C programming for years and I don't have enough exposure to Object oriented approaches. In C if I was developing some layered architecture then each layer has interfaces defined by function pointers. The advantage of that the whole layer can be replaced by just setting those function pointers at initialization to another layer.

I want the same thing but this time in Python. What is the coolest way to achieve that. To give a little background to my problem, I have a data generator which can output records to different mediums. The medium is specified at the configuration time. I don't want to use if or switch statements here. The best way was to use function pointers in C but what are the options available here in Python. Any Object oriented approaches are also appreciated.

Thanks

like image 553
Kanwar Saad Avatar asked Jan 18 '13 20:01

Kanwar Saad


2 Answers

in python functions are first-class data types.

def z(a):
    print(a)
def x(a):
    print "hi"

functions = [z,x]
y = functions[0]
y("ok") # prints "ok"
y = functions[1]
y("ok") # prints "hi"
like image 136
argentage Avatar answered Sep 21 '22 18:09

argentage


You can simply put the functions in a dict

{"type1": function1,
 "type2": function2,
 "type3": function3,
}.get(config_option, defaultfunction)(parameters, go, here)

default_function is called if none of the keys match

If you wish you can separate out the selection an the calling

selected_function = {"type1": function1,
                     "type2": function2,
                     "type3": function3,
                     }.get(config_option, defaultfunction)

some_instance = SomeClass(selected_function)
like image 24
John La Rooy Avatar answered Sep 20 '22 18:09

John La Rooy