Check if variable is an instance of a File object

Calvin Spealman ironfroggy at gmail.com
Fri Sep 15 03:50:48 EDT 2006


On 15 Sep 2006 00:18:14 -0700, sc_wizard29 at hotmail.com
<sc_wizard29 at hotmail.com> wrote:
> Hi everyone,
>
> Maybe these questions will sound strange to you, but I sometime have a
> hard time switching from Java to Python ;-)
>
> Let's say I have a function like this :
>
> def show_lines(file):
>         for next_line in file:
>                 ...
>
> What can I do to be sure that the input argument is indeed a 'File'
> object ?
>
> #1 : should I start by checking that 'file' is indeed an instance of a
> File object ? (and how do I do this ?)
> #2 : should I do nothing ? (but I don't like the idea of risking to
> have a runtime exception raised somewhere)
>
> Thanks for helping...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Do nothing!

The caller might pass you a file-like object, and you can never be
exactly sure. Duck typing rules in this case. If what they pass acts
like a file, then it must be a file (for as much as the function needs
to care, anyway). Don't want to risk an exception at runtime? Well,
isn't that what you would do if you explicitly checked for a file
object and had something else, anyway? Just assume its a file and if
there is an error it should propogate because one of the callers
messed up and should know that.



More information about the Python-list mailing list