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

George Sakkis george.sakkis at gmail.com
Wed Jul 25 13:14:15 EDT 2007


On Jul 24, 6:51 pm, Boris Dušek <boris.du... at gmail.com> wrote:

> 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)


Other replies show you how to tackle this in Python 2.x. Python 3K
will come closer to Java by formalizing the concept of abstract base
classes [1] and will most likely include a fine-grained hierarchy of
stream-like base classes [2].

George


[1] http://www.python.org/dev/peps/pep-3119/
[2] http://www.python.org/dev/peps/pep-3116/




More information about the Python-list mailing list