Python - test whether object is a builtin function

Try this:

>>> import types
>>> isinstance(pow, types.BuiltinFunctionType)
True
>>> def a():
    pass
>>> isinstance(a, types.BuiltinFunctionType)
False

It depends what you mean by “built-in”.

Using __builtins__

If you want to check that your function is one of the built-in functions in the Python interpreter you can use

>>> pow in __builtins__.__dict__.values()
True
>>> __builtins__.__dict__['pow']
<built-in function pow>

The Python interpreter has a number of built-in constants, functions, types, and exceptions, that are contained in the dictionary __builtins__.__dict__.

Using BuiltinFunctionType

If on the other hand you want to check if your function is of type BuiltinFunctionType you can use the types module

>>> import types
>>> isinstance(pow, types.BuiltinFunctionType)
True

Using inspect

Or inspect.isbuiltin (just a wrapper around isinstance(object, types.BuiltinFunctionType))

>>> import inspect
>>> inspect.isbuiltin(pow)
True

Note that the term “built-in” in BuiltinFunctionType means “written in C”.

Consider the following example:

>>> from math import factorial
>>> isinstance(factorial, types.BuiltinFunctionType)
True

The factorial function is of type BuiltinFunctionType but it's not a builtin function in the interpreter

>>> factorial in __builtins__.__dict__.values()
False

This is because the math module in Python consists of wrappers around the C math library functions.

Being able to detect a BuiltinFunctionType is useful because for functions written in Python one can inspect the source code without having to open the source files.

>>> import random
>>> isinstance(random.random, types.BuiltinFunctionType)
True
>>> inspect.getsource(random.random)
# returns TypeError
>>> isinstance(random.uniform, types.BuiltinFunctionType)
False
>>> from __future__ import print_function # if using Python 2.*
>>> print(inspect.getsource(random.uniform))
    def uniform(self, a, b):
        "Get a random number in the range [a, b) or [a, b] depending on rounding."
        return a + (b-a) * self.random()

The types module:

>>> import types
>>> types.BuiltinFunctionType
<type 'builtin_function_or_method'>

Though, if you look under the hood, you'll find it's not that different from what you're doing now.

So, in your case, use

isinstance(o, types.BuiltinFunctionType)

Tags:

Python