Python: determining if an object is a file?

I am writing some unit tests (using the unittest module) for my application and want to write something that can verify that the method I call returns a file object. Since this is not an easy call, I wonder what is the best practice for defining this?

So in the diagram:

possible_file = self.dao.get_file("anotherfile.pdf")
self.assertTrue(possible_file is file-like)

Perhaps I need to consider which specific interface this file object implements or what methods make it file-based, how do I want to support it?

Thank,

R

+5
source share
3 answers

" " , " ", , , read write ... , fileno, " ", StringIO cStringIO . " ", - !

, , . , FileLikeEnoughForMe abstractmethod isinstance , Python 2.6 : , hasattr, ( , .. -).

+7

Python , , . , , , write ing.

IO > isinstance. , , , .

(unittesting) , , :

thingy = ...
try:
    thingy.write( ... )
    thingy.writeline( ... )
    ...
    thingy.read( )
except AttributeError:
    ...
+4

Check if the returned object provides the interface you are looking for. For example, for example:

self.assert_(hasattr(possible_file, 'write'))
self.assert_(hasattr(possible_file, 'read'))
+2
source

All Articles