5

I want to pass a function to a function in Python. I know I can do this simply by putting the function name as a parameter, eg:

blah(5, function)

However, I want to pass the int() function and the float() function to this function. If I just put the function name in then it assumes I am referring to the int and float types not the functions for converting strings to ints and floats.

Is there a way to pass the function rather than the type?

robintw
  • 27,571
  • 51
  • 138
  • 205

2 Answers2

11

Just passing int and float is fine. You are right that this will actually pass type objects instead of functions, but that's not important. The important thing is that the passed object is callable, and calling the type objects will do what you expect.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    Why would you ever need to pass int as an argument? – Trufa Jun 22 '11 at 13:16
  • 4
    @Trufa: Just two examples: `defaultdict(int)` and `map(int, string_list)`. There are many more. – Sven Marnach Jun 22 '11 at 13:18
  • `sorted(['1','100','99'], key=int)` – John La Rooy Jun 22 '11 at 13:27
  • I was not trying to be a smartass (if that is how it sounded), I was just curious :) . And I did not phrase my question correctly, my question was: why would you need to pass int as a function, as it will always be callable as `int()` as it is built in, rather you need to pass is as the type, as you stated in your examples, have I understood you correctly? – Trufa Jun 22 '11 at 14:22
  • @Trufa: Sorry, I don't really understand what you are asking. – Sven Marnach Jun 22 '11 at 14:31
3

The type objects are what you want.

>>> def converter(value, converter_func):
...     new_value = converter_func(value)
...     print new_value, type(new_value)
... 
>>> converter('1', int)
1 <type 'int'>
>>> converter('2.2', float)
2.2 <type 'float'>
>>> 
John La Rooy
  • 295,403
  • 53
  • 369
  • 502