Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 724
Sophia Avatar asked Dec 08 '10 01:12

Sophia


2 Answers

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

like image 165
Chinmay Kanchi Avatar answered Sep 27 '22 15:09

Chinmay Kanchi


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
like image 38
Lennart Regebro Avatar answered Sep 27 '22 15:09

Lennart Regebro