Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function type?
#1
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 >>>
Reply
#2
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
Reply
#3
Thanks Larz, that'll do nicely. Big Grin
Reply
#4
You can do by like this:

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  determine parameter type in definition function akbarza 1 550 Aug-24-2023, 01:46 PM
Last Post: deanhystad
  i want to use type= as a function/method keyword argument Skaperen 9 1,777 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  match type with value in csv parsing function vinci 2 1,269 Jan-21-2022, 12:19 PM
Last Post: Larz60+
  Creating function inside classes using type wolfmansbrother 3 2,288 Mar-20-2020, 01:21 AM
Last Post: wolfmansbrother
  Type hinting - return type based on parameter micseydel 2 2,429 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Getting type from input() function in Python 3.0 leodavinci1990 7 3,662 Jul-29-2019, 08:28 PM
Last Post: avorane
  Type function does not work sunnyarora 2 2,450 Mar-15-2019, 10:50 AM
Last Post: sunnyarora
  Should a function ever be more permissive than its type hints? Shay 1 1,909 Mar-13-2019, 05:36 PM
Last Post: Larz60+
  Parameters type in a function girbinho 2 2,698 Oct-09-2018, 10:36 PM
Last Post: micseydel
  Why args type is always tuple, when passed it as argument to the function. praveena 5 5,276 Jan-16-2018, 09:07 AM
Last Post: praveena

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020