Is there a common way to check in Python if an object is any function type?

I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use callable() for this, but I don't want to include classes. The best I've come up with so far is:

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))

Is there a more future-proof way to do this check?

Edit: I misspoke before when I said: "Normally you could use callable() for this, but I don't want to disqualify classes." I actually do want to disqualify classes. I want to match only functions, not classes.

Asked by: Ryan888 | Posted: 27-01-2022

Answer 1

The inspect module has exactly what you want:

inspect.isroutine( obj )

FYI, the code is:

def isroutine(object):
    """Return true if the object is any kind of function or method."""
    return (isbuiltin(object)
            or isfunction(object)
            or ismethod(object)
            or ismethoddescriptor(object))

Answered by: Adrian548 | Posted: 28-02-2022

Answer 2

If you want to exclude classes and other random objects that may have a __call__ method, and only check for functions and methods, these three functions in the inspect module


should do what you want in a future-proof way.

Answered by: Ryan405 | Posted: 28-02-2022

Answer 3

if hasattr(obj, '__call__'): pass

This also fits in better with Python's "duck typing" philosophy, because you don't really care what it is, so long as you can call it.

It's worth noting that callable() is being removed from Python and is not present in 3.0.

Answered by: David502 | Posted: 28-02-2022

Answer 4

Depending on what you mean by 'class':

callable( obj ) and not inspect.isclass( obj )


callable( obj ) and not isinstance( obj, types.ClassType )

For example, results are different for 'dict':

>>> callable( dict ) and not inspect.isclass( dict )
>>> callable( dict ) and not isinstance( dict, types.ClassType )

Answered by: Emma813 | Posted: 28-02-2022

Similar questions

python - Which is more pythonic, factory as a function in a module, or as a method on the class it creates?

I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file. The calendar object just has a method that adds events as they get parsed. Now I want to create a factory function that creates a calendar from a file object, path, or URL. I've been using the iCalendar python module, w...

Is there a function in python to split a word into a list?

This question already has answers here:

Is there a function in Python to split a string without ignoring the spaces?

Is there a function in Python to split a string without ignoring the spaces in the resulting list? E.g: s="This is the string I want to split".split() gives me >>> s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] I want something like ['This',' ','is',' ', 'the',' ','string', ' ', .....]

unicode - Python: Use the codecs module or use string function decode?

I have a text file that is encoded in UTF-8. I'm reading it in to analyze and plot some data. I would like the file to be read in as ascii. Would it be best to use the codecs module or use the builtin string decode method? Also, the file is divided up as a csv, so could the csv module also be a valid solution? Thanks for your help.

How do I get the name of a function or method from within a Python function or method?

I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.

Lambda function for classes in python?

There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figur...

function pointers in python

I would like to do something like the following: def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) In python, is it possible to assign something like a function pointer?

python - Django foreign key access in save() function

Here's my code: class Publisher(models.Model): name = models.CharField( max_length = 200, unique = True, ) url = models.URLField() def __unicode__(self): return def save(self): pass class Item(models.Model): publisher = models.ForeignKey(Publisher) name = models.CharField( max_...

python - make a parent function return - super return?

there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function. >>> def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... >>> gs(1,2) # should return 2 >>> gs(1,1) # should return 1 >>> gs(5,3) # should return 6...

python - Safe escape function for terminal output

I'm looking for the equivalent of a urlencode for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal. I'm working in Python, but anything I ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python