This blog post is 15 years old! Most likely, its content is outdated. Especially if it's technical.
Python gurus are going to laugh at me for this one but I learnt it today; how to check if an object is callable. Before this I thought I was clever with this:
>>> def foo(): return "s"
>>> hasattr(foo, '__call__')
True
>>> hasattr(foo(), '__call__')
False
But there was an easier way. I discovered this by accident and looked it up in the documentation after. Use the builtin function called 'callable()':
>>> def foo(): return "s"
>>> callable(foo)
True
>>> callable(foo())
False
D'oh!
- Previous:
- Ugly one-liner to debug an object in Zope 31 March 2005
- Next:
- Python Cookbook arrived 05 April 2005
- Related by category:
- How much faster is Redis at storing a blob of JSON compared to PostgreSQL? 28 September 2019 Python
- Best practice with retries with requests 19 April 2017 Python
- fastest way to turn HTML into text in Python 08 January 2021 Python
- Fastest way to find out if a file exists in S3 (with boto3) 16 June 2017 Python
- Interesting float/int casting in Python 25 April 2006 Python
According to PEP 3000 the callable built-in function is going to be gone in Python 3.0. In the interest of staying compatible you may want to stick with the old way or call it and catch the exception as the previous comment mentioned. (PEP 3000 - http://www.python.org/peps/pep-3000.html)
Often it pays not to get fancy...
probably the best way (if you can afford to wait until the last possible moment) is to try making the call and catch the TypeError exception
I prefer not to use try and except statements. They look too wild and don't give any performance improvement.
Except for callables which might trigger nuclear weapons.
Good discovery. It helped you.
I tried callable(iter) and callable(candygram.link)
both returned true.....ya I was lazy to write a callable.
"the callable built-in function is going to be gone in Python 3.0"
in that case, hasattr(foo, '__call__') seems more logical (to a second hand reader) than catching the exception, in my opinion..
Python 3.3 shell log:
>>> def Foo():
return Foo
>>> f = Foo()
>>> f
<function Foo at 0x01F45930>
>>> callable(Foo)
True
>>> callable(Foo())
True
>>> callable(f)
True
Is that not what you expect?