Type testing

David Fisher python at rose164.wuh.wustl.edu
Wed Mar 15 19:06:49 EST 2000


> Is it possible to test for the type of an object (I mean, a built-in
object:
> a digit, a string, etc...)?
> I'm looking for something like:
> Result = isDigit(MyVariable)
> Result = isString(MyVariable)
> (Result = true | false, 1 | 0)
> Thanks.
>
Just to confuse the issue, I prefer to use isinstance() rather than type().
Like so:

>>> import types
>>> dir(types)
['BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType',
'CodeType', 'ComplexType', 'DictType', 'DictionaryType', 'EllipsisType',
'FileType', 'FloatType', 'FrameType', 'FunctionType', 'InstanceType',
'IntType', 'LambdaType', 'ListType', 'LongType', 'MethodType', 'ModuleType',
'NoneType', 'SliceType', 'StringType', 'TracebackType', 'TupleType',
'TypeType', 'UnboundMethodType', 'XRangeType', '__builtins__', '__doc__',
'__file__', '__name__']

>>> isinstance(3,types.IntType)
1
>>> isinstance('spam',types.IntType)
0
>>> isinstance('spam',types.StringType)
1
>>>





More information about the Python-list mailing list