Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting function object for int() and float() functions

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?

like image 205
robintw Avatar asked Jun 22 '11 13:06

robintw


People also ask

Is an int an object in Python?

Objects behave differently from one another according to what “type” a given object is. We reviewed several fundamental object types in Python: int , float , complex : the numerical types. bool : the boolean type.

Does return int or float Python?

It's always a float. It's inside the int call, though. On your second print statement: Python 3 is such that 9/2==4.5 . @Manaar // returns int if both operands are int and magnitude is always floor, Whereas / returns exact division.

Is function an object in Python?

Yes, python functions are full objects. They can have attributes and methods like objects. The functions can have data variables and even functions written inside of them.

Is print () a built-in function in Python?

In this article, we are going to see all the pre-defined functions that are available in Python. You have already used some of the Python built-in functions, for example, the print() function is used to output a string on the console. As of now, the latest version of Python 3.8 has 69 built-in functions.


2 Answers

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.

like image 63
Sven Marnach Avatar answered Sep 27 '22 23:09

Sven Marnach


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'>
>>> 
like image 34
John La Rooy Avatar answered Sep 28 '22 00:09

John La Rooy