Need instruction on how to use isinstance

MRAB python at mrabarnett.plus.com
Sun Jun 27 22:30:22 EDT 2010


Steven W. Orr wrote:
> I need to test an argument for a few different types.
> 
> I'm calling my function like this
> 
> arf = MyFunc(list)
> 
> What I want to do is to test for whether something is a string, tuple, list or
> function. It's that last one that's causing me a problem.
> 
> if isinstance(arg, (str, tuple, list)):
> 
> No problem, but there are a lot of types that the type function returns. If I
> have a simple function
> 
> def foo():
>     pass
> type(foo)
> prints out
> <type 'function'>
> 
> 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?
> 

 >>> def foo():
...     pass
...
 >>> import types
 >>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType', 
'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 
'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 
'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 
'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 
'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 
'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 
'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 
'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', 
'__builtins__', '__doc__', '__file__', '__name__', '__package__']
 >>> isinstance(f, types.FunctionType)
True
 >>>

> And last, what is the correct way to do it if this is not the right way?
> 
Why do you want to know what type it is? Do you want to do different
things depending on the type? If the same function can return instances
of any number of unrelated types/classes, then there's something wrong
in your design! (You should also learn what "duck typing" is!) :-)



More information about the Python-list mailing list