Check if object is file-like in Python

后端 未结 8 817
抹茶落季
抹茶落季 2020-12-01 00:02

File-like objects are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of

8条回答
  •  無奈伤痛
    2020-12-01 00:09

    Under most circumstances, the best way to handle this is not to. If a method takes a file-like object, and it turns out the object it's passed isn't, the exception that gets raised when the method tries to use the object is not any less informative than any exception you might have raised explicitly.

    There's at least one case where you might want to do this kind of check, though, and that's when the object's not being immediately used by what you've passed it to, e.g. if it's being set in a class's constructor. In that case, I would think that the principle of EAFP is trumped by the principle of "fail fast." I'd check the object to make sure it implemented the methods that my class needs (and that they're methods), e.g.:

    class C():
        def __init__(self, file):
            if type(getattr(file, 'read')) != type(self.__init__):
                raise AttributeError
            self.file = file
    

提交回复
热议问题