Sophia
Sophia

Reputation: 165

alternative to callable(),for use in Python 3

I looked at this thread but some of the concepts are above my current level. In Python 2.x, the callable() built-in method exists; is there a simple way to check to see if something is callable or not using Python 3?

Upvotes: 13

Views: 6520

Answers (3)

Lennart Regebro
Lennart Regebro

Reputation: 172309

callable() is back in Python 3.2.

If you need to use Python 3.1 (highly unlikely) then in addition to checking for __call__ there are also the following solutions:

  • 2to3 changes a callable(x) into isinstance(x, collections.Callable)

  • six uses

      any("__call__" in klass.__dict__ for klass in type(x).__mro__)
    

    Ie it checks for __call__ in the base classes. This reminds me that I should ask Benjamin why. :)

And lastly you can of course simply try:

try:
    x = x()
except TypeError:
    pass

Upvotes: 19

joeforker
joeforker

Reputation: 41787

It's back. Python 3.2 has callable(); there is no longer a need to use one of the less convenient alternatives.

Upvotes: 40

Chinmay Kanchi
Chinmay Kanchi

Reputation: 66003

You can just do hasattr(object_name, '__call__') instead. Unlike in Python 2.x, this works for all callable objects, including classes.

Upvotes: 9

Related Questions