Need instruction on how to use isinstance
Stephen Hansen
me+list/python at ixokai.io
Sun Jun 27 22:25:13 EDT 2010
On 6/27/10 7:09 PM, Steven W. Orr wrote:
> So, my question is, what value can I use as the 2nd arg to isinstance to see if
> foo is a function? And while I'm on the subject, what types does isinstance not
> support?
Does it have to be a function? -- There's quite a few things which are
function-y enough that you really should accept them even if they may
not be technically a /function/. Like a class instance with the __call__
method defined wrapping a function as a decorator. Or a bound method,
really.
In Python 2.x, you can use callable(fun) -- that goes away in Py3
though. But personally, I think this is the wrong approach.
I'm assuming you need to do some different sort of behavior based on if
its a str, tuple or list-- okay.
But, personally-- at that point, I would just *assume* the argument is a
function. And call it.
If it can't be called, its not a functiony-thing. You can either let
that traceback propagate, or just raise a TypeError "expected arg to be
a string, tuple, list or callable".
Then again, similarly I almost never want to test for if somethings a
tuple or list. I'd rather use it as a sequence type and see if it works:
while there's not as many 'sequency-like-things' out there as there are
function-like-things, there's still quite a few.
So personally, I'd check if its a string (can it be unicode or regular?
If so isinstance(x,basestring)).
Then I'd try to use it as a sequence, doing whatever I woulda done with
it sequence-like. If that works, great. If not, I'd try to call it.
Etc.
Then again it does depend on just what you're *doing* with the arg being
passed in.
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
More information about the Python-list
mailing list