0

In python, both classes and functions are callables, but in my case, I would only like to call something if it is a function.

Example Code:

class AClass:
    pass

def a_func():
    pass
type(AClass)

# Output: 
<class 'type'>

type(a_func)

# Output:
<class 'function'>

So, my actual question is how do I write an if saying something like:

if type(something) == <a function type>:
    # call the function 

I have tried doing this:

if isinstance(AClass, type):
    # passes through

if isinstance(a_func, type):
    # passes through too

So, checking with type in isinstance, I cannot get it to work.

I am comparing with type and isinstance(), any other way to solve it would be appreciated too.

piyush daga
  • 501
  • 4
  • 17

1 Answers1

0
from types import FunctionType

def a():
    pass

isinstance(a, FunctionType)
>>> True
TomMP
  • 715
  • 1
  • 5
  • 15
  • Although this code might (or might not) solve the problem, a good questions should also explain why this code helps and how it solves the problem. – BDL Mar 28 '19 at 10:32
  • That's a valid point, and I meant to expand on this, but then it was marked duplicate with a link to a much more extensive answer that used the same way I did here so I kind of just left it as it is. – TomMP Mar 28 '19 at 10:38