Skip to content

[Python] How to Determine Whether a Variable Is a Function

Today when I was rewriting a piece of code today, there was a requirement to pass a function into another function for its invocation. In addition, it is also necessary to determine whether a variable is a function when the function passed.

At present, I have tried to use the callable() function, and even the class of the callable() function will be judged as True, so it is not suitable for judging whether it is a function.

Finally, I found that you can use types.FunctionType in the modeling group in types as the data type of the function, and compare it with the variable to be determined in isinstance() for pairwise comparison.

But I am also worried that this method is too direct. If there is a better method, please feel free to leave a message below to let me know.

Although I can’t say how professional I am, but I at least hope that I can make progress in a better direction.


Determine whether a variable is a function

# coding: utf-8
import types


# a
def a(n):
    print(n)


# b
b = 10


def main():
    print("a:", isinstance(a, types.FunctionType))
    print("b:", isinstance(b, types.FunctionType))


if __name__ == "__main__":
    main()


Output:

a: True
b: False


As you can see, we can use this method to determine whether a variable is a function.


References


Read More

Tags:

Leave a Reply