Question

I am wiriting a script in which I would like to verify if a given argumente to a function is itself a function. I have checked in the IDLE the type() of that argument. Let us assume that the argumente is called a and that I know that a is a function.

When I type type(a) in the Shell, this gets printed: <class 'function'>

But if I try to type this: type(add) == function It gives me a NameError: name 'function' is not defined (That was not my only attempt, but if I put them all here this will get too long)

I think I understand that part, because I think function is not a keyword like int or float, which lets me do conditionals like type(3) == int

But, knowing this, how can I check if something is from a given built-in type, if that type does not have a specific keyword (or maybe, those keywords are not that well-known)

Thanks in advance.

Was it helpful?

Solution

You can use the isinstance built-in to check if the type of a variable conforms to a type of a function. Unfortunately, as there is no short hand to create a function type just like int you can import types and check with types.FunctionType

>>> import types
>>> isinstance(add, types.FunctionType)
True

you can also import isfunction from inspect to perform the same check

import inspect
inspect.isfunction(add)

OTHER TIPS

from inspect import isfunction

isfunction(a)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top