Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32947
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: isinstance(.., file) for Python 3 |
| Date | 2012-11-08 14:02 +0100 |
| Organization | None |
| References | <2pjsm9-p8h.ln1@satorlaser.homedns.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3433.1352379748.27098.python-list@python.org> (permalink) |
Ulrich Eckhardt wrote:
> Hi!
>
> I have two problems that are related and that I'd like to solve together.
>
> Firstly, I have code that allows either a file or a string representing
> its content as parameter. If the parameter is a file, the content is
> read from the file. In Python 2, I used "isinstance(p, file)" to
> determine whether the parameter p is a file. In Python 3, the
> returnvalue of open() is of type _io.TextIOWrapper, while the built-in
> class file doesn't exist, so I can't use that code.
>
> Secondly, checking for the type is kind-of ugly, because it means that I
> can't use an object that fits but that doesn't have the right type. In
> other words, it breaks duck-typing. This is already broken in the Python
> 2 code, but since I have to touch the code anyway, I might as well fix
> it on the way.
>
> If possible, I'm looking for a solution that works for Pythons 2 and 3,
> since I'm not fully through the conversion yet and have clients that
> might use the older snake for some time before shedding their skin.
>
> Suggestions?
In order of obviousness:
hasattr(p, "read")
not isinstance(p, str)
iter(p) is p
Or you change the interface
def f(*, contents=None, file=None):
if contents is None:
with open(file) as f:
contents = f.read()
... # work with contents
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
isinstance(.., file) for Python 3 Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2012-11-08 13:05 +0100
Re: isinstance(.., file) for Python 3 MRAB <python@mrabarnett.plus.com> - 2012-11-08 12:54 +0000
Re: isinstance(.., file) for Python 3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-11-08 12:56 +0000
Re: isinstance(.., file) for Python 3 Chris Angelico <rosuav@gmail.com> - 2012-11-08 23:57 +1100
Re: isinstance(.., file) for Python 3 Peter Otten <__peter__@web.de> - 2012-11-08 14:02 +0100
Re: isinstance(.., file) for Python 3 Duncan Booth <duncan.booth@invalid.invalid> - 2012-11-08 13:58 +0000
Re: isinstance(.., file) for Python 3 Stefan Behnel <stefan_ml@behnel.de> - 2012-11-08 16:14 +0100
csiph-web