Python - check if an object is an inline function

Is there a good way to check if an o object is a Python built-in function?

I know that I can use, for example

type(o) == type(pow)

because type (pow) is "builtin_function_or_method".

But is there a better way?

+5
source share
5 answers

Type module:

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

Although, if you look under the hood, you will find that it is not so different from what you are doing now.

So in your case use

isinstance(o, types.BuiltinFunctionType)
+9
source

Try the following:

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

import __builtin__
o in __builtin__.__dict__.values()

, CPython:

o in __builtins__.__dict__.values()

, .


>>> pow in __builtins__.__dict__.values()
True
>>> def a():
...   pass
...
>>> a in __builtins__.__dict__.values()
False
>>>
+2

, "".

__builtins__

, Python,

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

Python , , , __builtins__.__dict__.

BuiltinFunctionType

, , , BuiltinFunctionType, types

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

inspect

inspect.isbuiltin ( isinstance(object, types.BuiltinFunctionType))

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

, "" BuiltinFunctionType " C".

:

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

factorial BuiltinFunctionType,

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

, math Python Cmath.

BuiltinFunctionType , , Python, , .

>>> 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()
+1
source

Although some time has passed, other people may find my answer useful, as this question surfaced in my search for an answer.

If you are only interested in testing, this variable varis one of the following:
1. function
2. builtin_function_or_methodbut notmethod

I found the following test to work:

import types
def is_func(arg): return isinstance(arg, types.FunctionType) or\(isinstance(arg, types.BuiltinFunctionType) and arg.__self__ is None)

I hope I am right in my assumption, but the general idea is that if we were assigned builtin_methodit should be of a type, and not Noneassociated with it.

0
source

All Articles