Python Forum

Full Version: function type?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to work out how to test for an object being a function. Can you help? Huh

def my_func():
    print("Running my function...")
# my_func()



random_func =my_func

#   Print the type of object.
print(type(random_func))
#   _.

#   Return true or false to the question.
print("Is this a function?", isinstance(random_func, function))
#   _.


#   Run the function.
random_func()
Error:
<class 'function'> Traceback (most recent call last): File "/home/pi/Documents/Alan/Python/Test/function type.py", line 16, in <module> print("Is this a function?", isinstance(random_func, function)) NameError: name 'function' is not defined >>>
you can something like use this:
import types

JustForGiggles = True

def my_func():
    print('This is my function')

def tryit():
    if isinstance(my_func, types.FunctionType):
        print('my_func is a function')
    else:
        print('No, my_func is not a function sorry')

    if isinstance(JustForGiggles, types.FunctionType):
        print('JustForGiggles is a function')
    else:
        print('No, JustForGiggles is not a function sorry')

if __name__ == '__main__':
    tryit()
results:
Output:
my_func is a function No, JustForGiggles is not a function sorry
Thanks Larz, that'll do nicely. Big Grin
You can do by like this:

def is_function(x):
import types
return isinstance(x, types.FunctionType) \
or isinstance(x, types.BuiltinFunctionType)