Check if object is file-like in Python

后端 未结 8 823
抹茶落季
抹茶落季 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:13

    It is generally not good practice to have checks like this in your code at all unless you have special requirements.

    In Python the typing is dynamic, why do you feel need to check whether the object is file like, rather than just using it as if it was a file and handling the resulting error?

    Any check you can do is going to happen at runtime anyway so doing something like if not hasattr(fp, 'read') and raising some exception provides little more utility than just calling fp.read() and handling the resulting attribute error if the method does not exist.

提交回复
热议问题