473,395 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Check if variable is an instance of a File object

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...

Sep 15 '06 #1
9 5814
In <11*********************@b28g2000cwb.googlegroups. com>, sc_wizard29
wrote:
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 ?
Why do you want to be sure? I would even rename the argument:

def show_lines(lines):
for line in lines:
...

This works with *every* iterable that contains "lines". No need to
"cripple" it with a type checking.
#2 : should I do nothing ? (but I don't like the idea of risking to
have a runtime exception raised somewhere)
Then don't use Python. Except `SyntaxError` almost every
exception is a runtime one.

And what do you do if you check for `file` and it isn't such an instance?
Raise an exception? A no, that's something you don't like. So what else? ;-)

Ciao,
Marc 'BlackJack' Rintsch
Sep 15 '06 #2
On 15 Sep 2006 00:18:14 -0700, sc*********@hotmail.com
<sc*********@hotmail.comwrote:
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.
Sep 15 '06 #3

Marc 'BlackJack' Rintsch a ecrit :
And what do you do if you check for `file` and it isn't such an instance?
Raise an exception? A no, that's something you don't like. So what else? ;-)
Well, I prefer the idea of raising my *own* exception to the idea of
having an unknown behavior occur (for ex : what if the argument is NOT
a File, but is "itereable" ?)

But anyway, I guess the most "pythonic" way is to do nothing ;-)
One more question : how to test if 'file' is a File object ?

Sep 15 '06 #4
sc*********@hotmail.com wrote:
>
Marc 'BlackJack' Rintsch a ecrit :
>And what do you do if you check for `file` and it isn't such an instance?
Raise an exception? A no, that's something you don't like. So what
else? ;-)

Well, I prefer the idea of raising my *own* exception to the idea of
having an unknown behavior occur (for ex : what if the argument is NOT
a File, but is "itereable" ?)

But anyway, I guess the most "pythonic" way is to do nothing ;-)
Indeed, don't waste time to make your code less general. Why would you want
to prevent your show_lines() function from processing a list of strings or
a StringIO?
One more question : how to test if 'file' is a File object ?
The file type is actually spelt lowercase, so 'file' is not a good idea as a
variable name.
>>f = file("tmp.txt")
isinstance(f, file) # isinstance(f, open) looks odd
True

isinstance() returns True for subclasses, if you don't want that either:
>>type(f) is file
True

Peter
Sep 15 '06 #5
Thanks for your help peter !

Sep 15 '06 #6
sc*********@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:
...
OT : this will shadow the builtin file type. Avoid shadowing builtin
types if you value your mental sanity !-)
What can I do to be sure that the input argument is indeed a 'File'
object ?
Why do you think you need "to be sure that the input argument is indeed
a 'File' object" ? As long as the object passed in is able to answer to
the messages you'll send to it, everything's fine, isn't it ? And if it
fails, well, you'll find out pretty soon...
#1 : should I start by checking that 'file' is indeed an instance of a
File object ?
Unless you have a *very* compelling reason to do so (and I can't imagine
one here), definitively, no. FWIW, it's pretty common in Python to pass
file-like objects (StringIo comes to mind... but there are lots of other
cases) to functions expecting a file object. And remember that Python
doesn't relies on inheritence for typing. Also, for what you showed of
your code, any iterable seems ok !-)
(and how do I do this ?)
isinstance(obj, *classes)

OT : note that in your case, since the arg name 'file' shadows the
builtin type, you'll have hard time using it !-)
#2 : should I do nothing ?
Yes. Well, IMHO.
(but I don't like the idea of risking to
have a runtime exception raised somewhere)
Err... What exactly do you intend to do if the object passed in is not a
file ? Raise a TypeError ? If so, when do you think it will fires ? Yes
my friend- at runtime !-)

As you noticed, switching from Java to Python requires some mental
adjustements... Not fearing runtime exceptions is one of them. Thinking
in terms of implied interface is another one. In your above code, you
really don't care if the objects is a file or not - you just care if the
object support the subset of the file interface you intend to use. And
this, you'll only know at runtime.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 15 '06 #7
sc*********@hotmail.com wrote:
Marc 'BlackJack' Rintsch a ecrit :
>And what do you do if you check for `file` and it isn't such an instance?
Raise an exception? A no, that's something you don't like. So what else? ;-)

Well, I prefer the idea of raising my *own* exception to the idea of
having an unknown behavior occur
The behavior in case of an uncaught exception is pretty well defined :
your app crashes with an error message and a traceback. Note that
nothing prevents you to try and catch most execptions at the top-level
and do whatever seems appropriate here (log the error, try to see if the
app just display the error and continue with another task or if it's
time to suicide, etc)...
(for ex : what if the argument is NOT
a File, but is "itereable" ?)
hard to tell without knowing the rest of the code, but if it's something
like this :

def show_lines(fileobj):
for line in fileobj:
print line

it will just work...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 15 '06 #8

sc*********@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
it ?

Here is an example :

class ProgrammerError(Exception): pass

def function(myFile):
if not isinstance(myFile, file):
raise ProgrammerError
for line in myFile:
print myFile

try:
function('something')
except ProgrammerError:
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'.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
Thanks for helping...
Sep 15 '06 #9
Bruno Desthuilliers wrote:
sc*********@hotmail.com wrote:
#1 : should I start by checking that 'file' is indeed an instance of a
File object ?

Unless you have a *very* compelling reason to do so (and I can't imagine
one here), definitively, no. FWIW, it's pretty common in Python to pass
file-like objects (StringIo comes to mind... but there are lots of other
cases) to functions expecting a file object. And remember that Python
doesn't relies on inheritence for typing. Also, for what you showed of
your code, any iterable seems ok !-)
Well, not quite; string comes to mind as a common counter example.
Still, a usually better way to handle a string argument than raising an
exception is wrap it in StringIO:

from cStringIO import StringIO

def show_lines(text):
if isinstance(text,basestring):
text = StringIO(text)
for line in text:
# do something
George

Sep 15 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Shu-Hsien Sheu | last post by:
Hi, Does the seek method would close the file object after using a for loop? My program looks like this: f = open('somefile', 'r') for lines in f: some operations f.seek(0)
5
by: John Marshall | last post by:
Hi, Does anyone see a problem with doing: data = file("tata").read() Each time this is done, I see a new file descriptor allocated (Linux) but not released. 1) Will there ever be a point...
1
by: Matthew Thorley | last post by:
I've been using tarfile like this import tarfile tar = tarfile.open('path_to_tar_archive', 'r:gz') But I need to use it like this: archive = open('path_to_tar_archive', 'r') tar =...
19
by: wetherbean | last post by:
Hi group..I am writing a playlist management protocol where I have a file that holds all the playlists and a file that holds all the songs....before a playlist is created I need to check to see if...
5
by: jez123456 | last post by:
Hi, I’ve written a c# program to compact certain msaccess databases. The way this works is to compact say C:\test1.mdb to C:\temp.mdb, then delete C:\test1.mdb and rename C:\temp.mdb as...
2
by: Frank | last post by:
Hi, I've got a problem with calling a unmanged function : function call in the .H file : DWORD _stdcall DoCmdRequest(long lMode, long * plTagType); my definition in C#
3
by: Sridhar | last post by:
Hi, I have placed the Sql Connection in the App.Config of the project. When I am trying to read this value from the project it is giving the error "Object Reference not set to an instance of...
3
by: Mayur H Chauhan | last post by:
All, I am working on one product where we need to check for physical file is in use (if it is open by other application). What I found out is that I am able to trap for those files whose attribute...
3
by: mironline | last post by:
dear friends I want to Create new instance of object with using Type with this code; class Myclass(){} class OtherClass() { Myclass mc = CreateNewInstance(typeof(MyClass));
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.