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?

2 Answers 2

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.

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

5 Comments

Why would you ever need to pass int as an argument?
@Trufa: Just two examples: defaultdict(int) and map(int, string_list). There are many more.
sorted(['1','100','99'], key=int)
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: Sorry, I don't really understand what you are asking.
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'>
>>> 

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.