[Tutor] code improvement for beginner ?

Jacob S. keridee at jayco.net
Sat Oct 22 01:05:58 CEST 2005


> Text mode is the default, you have to specify the 'b' if you want binary 
> mode. And open() seems to accept any mode quite happily:
>
> >>> f=open('build.xml', 'rt')
> >>> f
> <open file 'build.xml', mode 'rt' at 0x0096C9B0>
> >>> f.close()
> >>> f=open('build.xml', 'rabcd')
> >>> f
> <open file 'build.xml', mode 'rabcd' at 0x0096C9F8>
>
> Kent

I'll bet you'll find that open() is coded something like the following

def open(filename,mode="r"):
    if mode = 'w':
        dosomething()
    if mode = 'wb':
        dosomething()
    if mode = 'w+':
        dosomething()
    if mode = 'rb':
        dosomething()
    ...
    else:
        dosomething()  # Where this assumes you are using default mode "r"

This flow control with emphasis on the else means that if the mode doesn't 
match anything other than "r", then return file object mode "r"

Let's see, now that I'm checking whether that's true, it doesn't quite match 
up. A file that's opened with "r" will check to see whether the file exists 
or not, whereas a file opened with nonsense does not. Ahh. That's because 
you can write to a file opened with nonsense. So instead the function (if it 
were written in python and not C) would probably look like this instead.

def open(filename, mode="r")
    if mode = "r":
        dosomethingread()
    if mode = "rb":
        dosomethingreadbin()
    if mode = "w+":
        dosomethingwriteupd()
    ...
    else:
        dosomethingwrite()       # Where write is in the else clause, but 
read is the default value for mode

Phew.

This seems strange. Why don't they put write in the control flow above with 
a raise statement in the else clause?

HTH,
Jacob



More information about the Tutor mailing list