To find out if a variable is a function or not?

Asked 2 years ago, Updated 2 years ago, 174 views

How do I find out if the variable x is a function or just a general variable?

When x is pointing to a function, type(x) = <type 'function'> I want to win isinstance(x, function) I wrote it like this, but there's an error. What should I do?

Traceback (most recent call last): File "", line 1, in ? NameError: name 'function' is not defined The reason I picked that is because

function python detect

2022-09-22 22:28

1 Answers

Type buitin without constructor is located in the types module. Therefore, you must import the types module and pass types.FunctionType as a parameter for isinstance.

import types
def myfunction():
    pass
myFunc = myfunction
print isinstance(myFunc, types.FunctionType) #True

If you don't want to import modules separately, use the following method

All functions have the attribute __call___ because they can "call". Therefore, by determining if the object has the attribute __call___ as follows: You can distinguish functions.

def myfunction():
    pass
myFunc = myfunction
print hasattr(myFunc, "__call__") #It's a function, so it's true

myVal = 3
print hasattr(myVal, "__call__") #False because it is an int-type object


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.