Need instruction on how to use isinstance

Steven W. Orr steveo at syslang.net
Sun Jun 27 23:04:29 EDT 2010


On 6/27/2010 10:25 PM, Stephen Hansen wrote:
> 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.

Ok, you just asked great questions, and your questions were based on what I
didn't tell you.

I'm trying to teach myself about how __metaclass__ can be used as a substitute
for LSD. ;-)

So, instead of writing a class that does typechecking on its arguments at
instantiation time, I'm writing a metaclass that allows the class to announce
what sort of values it specifically will be expecting after instantiation.

The model I'm using is something I've found that

http://cleverdevil.org/computing/78/

So, the basic idea is

>>> class Person(Enforcer):
    ...    name = Field(str)
    ...    age = Field(int)
    ...    ff = Field(function)

but there's no factory function called function.

Does this help?

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


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



More information about the Python-list mailing list