I am reading a Python book for Pyton 2.5 (But I am doing Python 3). I am at the chapter classes and I got this part;

"You can check whenever the function attribute was callable."

callable(tc,'talk',None)

In Python3 we do not have callable anymore, so I checked on the internet, how do it, and I found this:

hasattr(anything, '__call__')

Now here are my question:

1.) What do I have to put in the "anything" part? a function of a class?

2.) What does callable actually do? What does callable actually means? To check when was the last time I used that function..? What does it do? And what kind of situatins would I use this?

Thanks in advance

Here is an example ...

# exploring Python2 callable(object)
# in Python3 this changes to (need to import collections) ...
# isinstance(object, collections.Callable), 

class C:
    pass

def funk():
    return 1234

# notice the () used to call a class or function
instance_c = C()
numbers = funk()

print(callable(C))           # True
print(callable(funk))        # True

# class instances and variables are not callable
# x = numbers()  would give an error
# TypeError: 'int' object is not callable

print(callable(instance_c))  # False
print(callable(numbers))     # False

# the instance of a class is callable if the class has method __call__
# generally used to pass arguments to the class instance call
class D:
    def __call__(self):
        pass

instance_d = D()

print(callable(D))           # True
print(callable(instance_d))  # True

Edited 5 Years Ago by vegaseat: n/a

I think it is best to avoid the use of the built in function callable , because Guido van Rossum thought it was a mistake in the python language (perhaps because of similar questions, what does callable actually means). That's why it was removed in python 3. I like the hasattr(x, __call__) , which is not ambiguous. You could also define your own callable like this

from functools import partial

def my_callable(x):
  try:
    partial(x) # this fails if x is not callable
    return True
  except TypeError:
    return False

Or without modules:

def callable(f):
    try:
        f()
        return True
    except AttributeError:
        return False
    except TypeError:
        return False

Or you can try to call it and catch exception in your code. But there is the collections.Callable, like vegaseat said.

Edited 5 Years Ago by pyTony: n/a

Comments
clever

Or without modules:

def callable(f):
    try:
        f()
        return True
    except AttributeError:
        return False
    except TypeError:
        return False

Or you can try to call it and catch exception in your code. But there is the collections.Callable, like vegaseat said.

callable(f), whatever it is, should not actually call f().

This question has already been answered. Start a new discussion instead.