7

I have a variable f. How can I determine its type? Here is my code, typed into a Python interpreter, showing that I get an error using the successful pattern of the many examples I have found with Google. (Hint: I am very new to Python.)

>>> i=2; type(i) is int
True
>>> def f():
...     pass
... 
>>> type(f)
<class 'function'>
>>> type(i)
<class 'int'>
>>> type(f) is function
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> f=3
>>> type(f) is int
True
wjandrea
  • 28,235
  • 9
  • 60
  • 81
David Epstein
  • 433
  • 4
  • 14
  • 3
    You already got its type, by using `type`. There's no `function` built-in variable bound to that type; the name a class knows itself by doesn't imply the existence of a variable with that name. – user2357112 Jan 02 '19 at 16:02
  • Have a look here: https://stackoverflow.com/questions/402504/how-to-determine-a-python-variables-type – Jelmer Jan 02 '19 at 16:02
  • Just in case, that you expected Python to return also the result type of the function: this is not possible in a dynamic language, since different Returns could return different type results. Possibly [function annotations](https://www.python.org/dev/peps/pep-3107/) of Python 3 may assist you, but they are not enforced. – guidot Jan 02 '19 at 16:06

1 Answers1

12

The pythonic way to check the type of a function is using isinstance builtin.

i = 2
type(i) is int  # not recommended
isinstance(i, int)  # recommended

Python includes a types module for checking functions among other things.

It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.

So, to check if an object is a function, you can use the types module as follows

def f():
    print("test")

import types
type(f) is types.FunctionType  # Not recommended but it does work
isinstance(f, types.FunctionType)  # Recommended.

However, note that it will print false for builtin functions. If you wish to include those as well, then check as follows

isinstance(f, (types.FunctionType, types.BuiltinFunctionType))

However, use the above if you only want specifically functions. Lastly, if you only care about checking if it is one of function, callable or method, then just check if it behaves like a callable.

callable(f)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
  • 4
    one can, of course, just do `def f(): pass; function = type(f)` – juanpa.arrivillaga Jan 02 '19 at 16:48
  • a clever hack. @juanpa.arrivillaga I wanted to post a canon answer without workarounds, but that definitely works as well. (Point to note is that it behaves like `types.FunctionType` in the sense that it evaluates to false for builtins.) edit: because it is, as pointed out by Juanpa. – Paritosh Singh Jan 02 '19 at 16:52
  • 4
    It doesn't behave *like it*, it **is** `types.FunctionType` – juanpa.arrivillaga Jan 02 '19 at 16:53