Python Glossary Русский

all Python 3typesterm

types.FunctionType

function types

The type of functions written in Python with def or lambda. Use it to tell a real function apart from a built-in, a class or an object with __call__.

Syntax

isinstance(obj, types.FunctionType)

isinstance(x, types.FunctionType) and callable(x) answer different questions. callable says "can be called", which is True for len, for a class, for functools.partial and for any object with __call__. FunctionType means "a function made by def or lambda": it has __code__, __defaults__ and __closure__, and only it can be inspected down to its code. A method taken from an instance (obj.m) is a MethodType, not a FunctionType. If you only want to call it, check callable; FunctionType is for decorators and introspection. types.LambdaType is the very same object: LambdaType is FunctionType.

Examples

import functools
import types
def f(x):
    return x
class Greeter:
    def __call__(self):
        return 'hi'
for obj in (f, lambda: 0, len, Greeter, Greeter(), functools.partial(f, 1)):
    print(isinstance(obj, types.FunctionType), callable(obj))
# → True True / True True / False True / False True / False True / False True
import types
print(types.LambdaType is types.FunctionType)  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy