Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the functions type in python3 [duplicate]

in python 3 every things are objs , functions too. functions are first-class citizens that mean we can do like other variables.

>>> class x:
    pass

>>> 
>>> isinstance(x,type)
True
>>> type(x)
<class 'type'>
>>> 
>>> x=12
>>> isinstance(x,int)
True
>>> type(x)
<class 'int'>
>>> 

but functions are diffrent ! :

>>> def x():
    pass

>>> type(x)
<class 'function'>
>>> isinstance(x,function)
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    isinstance(x,function)
NameError: name 'function' is not defined
>>>

why error ? what is python functions type ?

like image 727
Zero Days Avatar asked Aug 15 '15 05:08

Zero Days


2 Answers

@falsetru's answer is correct for function's type.

But if what you are looking for is to check whether a particular object can be called using () , then you can use the built-in function callable(). Example -

>>> def f():
...  pass
...
>>> class CA:
...     pass
...
>>> callable(f)
True
>>> callable(CA)
True
>>> callable(int)
True
>>> a = 1
>>> callable(a)
False
like image 188
Anand S Kumar Avatar answered Oct 02 '22 00:10

Anand S Kumar


You can use types.FunctionType:

>>> def x():
...     pass
...
>>> import types
>>> isinstance(x, types.FunctionType)
True
like image 43
falsetru Avatar answered Oct 02 '22 00:10

falsetru