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

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.

commented: clever +13

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().

Yes, that makes sense, function could do anything and could take ages.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.