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 from file
. It is realization of the Duck Typing concept.
It is considered a good practice to allow a file-like object everywhere where a file is expected so that e.g. a StringIO or a Socket object can be used instead a real file. So it is bad to perform a check like this:
if not isinstance(fp, file): raise something
What is the best way to check if an object (e.g. a parameter of a method) is “file-like”?
Advertisement
Answer
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.