Python - test whether object is a builtin function

后端 未结 5 904
面向向阳花
面向向阳花 2020-12-19 06:16

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)

beca

5条回答
  •  死守一世寂寞
    2020-12-19 06:37

    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']
    
    

    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()
    

提交回复
热议问题