Kwissle

My real-time quiz battle game Kwissle.com

Crosstips.org

My fun Crossword solver project. Crosstips.org & Krysstips.se

Kung Fu

Fujian White Crane Kung Fu

Photos

Photoalbum, both old and new.

Twitter

Follow me on Twitter

Contact me

My contact details and how to contact me.

 

KungFuPeople.com
Do you train Kung Fu?
Or know someone who does?
Then check out KungFuPeople.com


Mobile version of this page Mobile version of this page


 
Python

callable Python objects

http://docs.python.org/lib/built-in-funcs.html

2nd of April 2005

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!



Comment

Anonymous - 3rd April 2005  [«« Reply to this]
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
Peter Bengtsson - 3rd April 2005   [«« Reply to this]
I prefer not to use try and except statements. They look too wild and don't give any performance improvement.
Anonymous - 15th September 2008   [«« Reply to this]
Except for callables which might trigger nuclear weapons.
James Gray - 3rd April 2005  [«« Reply to this]
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...
Eeswar Ravi - 10th January 2009  [«« Reply to this]
Good discovery. It helped you.

I tried callable(iter) and callable(candygram.link)

both returned true.....ya I was lazy to write a callable.
Anonymous - 28th July 2009  [«« Reply to this]
"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..
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.