Base class for file-like objects? (a.k.a "Stream" in Java)

Boris Dušek boris.dusek at gmail.com
Tue Jul 24 18:51:30 EDT 2007


Hello,

(sorry to begin with Java in a Python list ;-)
in Java, when I want to pass input to a function, I pass
"InputStream", which is a base class of any input stream.

In Python, I found that "file" objects exist. While specifying
argument types in Python is not possible as in Java, it is possible to
check whether an object is an instance of some class and that's what I
need - I need to check if an argument is a "file"-like object, and if
yes, behave accordingly, if not, treat the argument as string with
URL.

But I am afraid there is no such a base class - I tried the following:

>>> import urllib
>>>
>>> f = open("test.txt", "r")
>>> g = urllib.urlopen("http://www.google.com/")
>>>
>>> isinstance(f, file)
True
>>> isinstance(f, file)
False
...

Is there some base class to "file"-like (or "stream"-like) objects in
Python? And if not, is it at least planned for Python 3.0?

Thanks for any suggestions,
Boris Dušek

P.S.: The code should finally look in esence something like this:

if isinstance(f, file):
   pass
elif isinstance(f, string):
   f = urllib.urlopen(f)
else:
   raise "..."
process_stream(f)




More information about the Python-list mailing list