tags:

views:

77

answers:

3

It used to be in Python (2.6) that one could ask:

isinstance(f, file)

but now "file" is undefined (using Python 3.0)

What is the proper method for checking to see if a variable is a file now? The What'sNew docs didn't mention this...

+1  A: 
def read_a_file(f)
    try:
        contents = f.read()
    except AttributeError:
        # f is not a file

substitute whatever methods you plan to use for read. This is optimal if you expect that you will get passed a file like object more than 98% of the time. If you expect that you will be passed a non file like object more often than 2% of the time, then the correct thing to do is:

def read_a_file(f):
    if hasattr(f, 'read'):
        contents = f.read()
    else:
        # f is not a file

This is exactly what you would do if you did have access to a file class to test against. (and FWIW, I too have file on 2.6) Note that this code works in 3.x as well.

aaronasterling
Not a bad general solution in absence of more direct support within the language....
Mark J
@Mark J. This is not a workaround. This is __THE CORRECT PYTHONIC WAY__ to address testing if you are dealing with a file or not. This way, your code works with any object that supports the minimal interface which it requires.
aaronasterling
Alright, I'll accept that. Though, I believe this is a wart in 3.0 not to be able to check an instance like all other types.
Mark J
@Mark. You're not supposed to check any types in python. I normally downvote answers that suggest doing so for no other reason. You are supposed to use one of the two methods that I've presented for all of your type checking needs.
aaronasterling
A: 

Works for me on python 2.6... Are you in a strange environment where builtins aren't imported by default, or where somebody has done del file, or something?

Doug
A: 

I just checked this out on my Python 2.6:

>>> f = open('filepath', 'r'):
>>> type(f) == file
True

Hope that solves your problem

inspectorG4dget
I don't know who downvoted this or why. I would appreciate some feedback.
inspectorG4dget
All the non-accepted answers were downvoted to -1. I'm not sure why either.
Doug
Downvotes were probably made as an attempt to reduce clutter on answers related to <vers3 (which are no longer relevant).
Mark J