Python - test whether object is a builtin function

后端 未结 5 907
面向向阳花
面向向阳花 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:43

    Although some time has passed, perhaps other people will find my answer useful since this question has popped up in my search for an answer.

    In case you are only interested in testing rather a given variable var is one of the following:
    1. function
    2. builtin_function_or_method but not a method

    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)

    Hope i am correct in my assumption, but the general idea is that if we have been given a builtin_method it must have a type not None associated with it.

提交回复
热议问题