Base class for file-like objects? (a.k.a "Stream" in Java)
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue Jul 24 21:58:17 EDT 2007
En Tue, 24 Jul 2007 19:51:30 -0300, Boris Dušek <boris.dusek at gmail.com>
escribió:
> 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.
No, it's not what you need, it's what you *think* you need :)
> P.S.: The code should finally look in esence something like this:
Posting this is much better that saying what you think you need.
> if isinstance(f, file):
> pass
> elif isinstance(f, string):
> f = urllib.urlopen(f)
> else:
> raise "..."
> process_stream(f)
I can imagine that process_stream is something like this:
def process_stream(f):
...
data = f.read()
...
or similar. Then, you dont need a file object: you need something with a
read() method. So, this is what you should check in your code above.
if hasattr(f, "read"):
pass
elif isinstance(f, basestring):
f = urllib.urlopen(f)
else:
raise TypeError, "Expecting either a readable file-like object or an URL"
process_stream(f)
Or perhaps:
if isinstance(f, basestring):
f = urllib.urlopen(f)
process_stream(f)
and just let the exception happen below at f.read - which explains itself
rather well.
--
Gabriel Genellina
More information about the Python-list
mailing list