Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - test whether object is a builtin function

Tags:

python

Is there a nice way to check whether object o is a builtin Python function?

I know I can use, for example

type(o) == type(pow)

because type(pow) is 'builtin_function_or_method'.

But is there some nicer way?

like image 263
Guy Adini Avatar asked Sep 10 '12 08:09

Guy Adini


People also ask

How do you check if an object is a function in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

How do you check if an instance is a function Python?

The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).

How do you check the type of an object in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you check if an object is a certain class Python?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .


1 Answers

You can check if builtins has it as an attribute and it's callable. Samples:

>>> import builtins
>>> hasattr(builtins, 'max')
True
>>> hasattr(builtins, 'abs')
True
>>> hasattr(builtins, 'aaa')
False
>>> hasattr(builtins, 'True')
True
>>> callable(abs)
True
>>> callable(True)
False
>>> hasattr(builtins, 'max') and callable(max)
True
>>> hasattr(builtins, 'True') and callable(True)
False
like image 139
snoopyjc Avatar answered Sep 27 '22 20:09

snoopyjc