Python 3.3.2 check that object is of type file

前端 未结 1 661
借酒劲吻你
借酒劲吻你 2020-12-30 04:34

I\'m porting from Python 2.7 to Python 3.3.2. In Python 2.7, I used to be able to do something like assert(type(something) == file), but it seems that in Python

1条回答
  •  旧时难觅i
    2020-12-30 05:03

    Python 3 file objects are part of the io module, test against ABC classes in that module:

    from io import IOBase
    
    if isinstance(someobj, IOBase):
    

    Don't use type(obj) == file in Python 2; you'd use isinstance(obj, file) instead. Even then, you would want to test for the capabilities; something the io ABCs let you do; the isinstance() function will return True for any object that implements all the methods the Abstract Base Class defines.

    Demo:

    >>> from io import IOBase
    >>> fh = open('/tmp/demo', 'w')
    >>> isinstance(fh, IOBase)
    True
    >>> isinstance(object(), IOBase)
    False
    

    0 讨论(0)
提交回复
热议问题