要检查一个实例是' StringIO'

时间:2013-02-06 17:35:43

标签: python stringio

>>> import cStringIO
>>> a = cStringIO.StringIO()
>>> type(a)
<type 'cStringIO.StringO'>
>>> isinstance(a, cStringIO.StringO)

Traceback (most recent call last):
  File "<pyshell#223>", line 1, in <module>
    isinstance(a, cStringIO.StringO)
AttributeError: 'module' object has no attribute 'StringO'

我需要将一些数据(类似文件的对象)返回给wsgi app。如果数据不是cStringIO对象(因为我不想再次重新读取内存),那么该数据将加载到cStringIO对象,但isinstance(a,cStringIO.StringO)或isinstance(a,cStringIO.StringIO)都抛出例外。如何检查实例是否为cStringIO对象?

1 个答案:

答案 0 :(得分:8)

改为使用cStringIO.InputType and cStringIO.OutputType

>>> import cStringIO
>>> s = cStringIO.StringIO('output')
>>> isinstance(s, cStringIO.InputType)
True
>>> s = cStringIO.StringIO()
>>> isinstance(s, cStringIO.OutputType)
True