Eli Korvigo
Eli Korvigo

Reputation: 10503

Python 2: function abstract type

I have a function that accepts a mapping that can be either a dictionary of a function, so I need to distinguish them. Usually I use some Abstract Base Class from collections and isinstance/issubclass to check argument types, but there is no ABC for functions. I know I can do hasattr(mapping, "__call__"), but I'm wondering whether there is something more specific for functions.

Upvotes: 0

Views: 50

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160477

You could use the types module for this which has, among others, FunctionType defined:

>>> import types
>>> types.FunctionType
<type 'function'>
>>> def foo(): pass
... 
>>> isinstance(foo, types.FunctionType)
True

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122376

You could use callable(obj) which is available in Python 2.7 and Python 3.2+ but not in Python 3.0 or Python 3.1.

You can also use types.FunctionType:

isinstance(obj, types.FunctionType)

Upvotes: 2

Related Questions