how to find out if an object is a class?

Stefan Behnel stefan_ml at behnel.de
Sun Aug 10 01:14:05 EDT 2008


Steven D'Aprano wrote:
> On Fri, 08 Aug 2008 16:38:14 +0200, Stefan Behnel wrote:
>> Miles wrote:
>>> On Fri, Aug 8, 2008 at 2:31 AM, Stefan Behnel wrote:
>>>> I recently had the reverse case that a (stupidly implemented)
>>>> extension module required a callback function and I wanted to pass a
>>>> function wrapped in a wrapper object. That failed, because it
>>>> specifically checked for the argument being a function, not just a
>>>> callable object. I had to pull quite a number of tricks to reimplement
>>>> the wrapper class as a function (thank god, it's Python!).
>>> You really only needed one trick:
>>>
>>> def functionize(callable):
>>>     return lambda *args, **kwargs: callable(*args, **kwargs)
>> Congratulations, you found the trivial case.
> 
> What other cases are there? It takes any callable, and returns a function 
> that calls the callable. What else do you need? [...] What am I missing?

The words "stupidly implemented" above? :)

I have to set the callback in more than one place and (believe it or not) the
library behaves (slightly) different when you pass different callbacks. The
right way to use the above approach would be to wrap the callback right before
passing it into the library - which I can't do, as that would give me a
different function object each time. Also, most of the time I actually pass a
function, except in one case where I need a wrapper for an existing function.
So the solution I chose was to change the original wrapper class itself
instead of re-wrapping it, so that I get the expected object right away.

As usual, it's all about the details.

Stefan



More information about the Python-list mailing list