Check if variable is an instance of a File object
fuzzyman at gmail.com
Fri Sep 15 14:49:04 CEST 2006
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)
It depends how you want to do your exception handling. Assuming you
have passed in an object that isn't a file, how do you want to handle
Here is an example :
class ProgrammerError(Exception): pass
if not isinstance(myFile, file):
for line in myFile:
print 'I did something wrong'
Writing tests that check your code doesn't do this would be a better
approach. This is 'strong testing' as opposed to 'strong typing'.
> Thanks for helping...
More information about the Python-list