PEP 308: A PEP Writer's Experience - PRO
Andrew Dalke
adalke at mindspring.com
Mon Feb 10 02:25:47 EST 2003
Andrew Koenig
> Here's a different example that you may find more persuasive.
>
> Recall that many programs take file names as parameters, and some of
> those use the convention that if the file name is "-", the program
> should process the standard input instead of opening a file.
...
> Then I would like to be able to write this:
>
> print "Processing", "<stdin>" if filename == "-" else filename
>
> You might claim that it is better to write
>
> print "Processing",
> if filename == "-":
> print "<stdin>"
> else:
> print filename
Actually, you still need to open the file, correct? If you use
the if/else above then you need to check the extension twice,
which seems more fragile in the face of maintainence. Instead,
it should be
if filename == "-":
displayname = "<stdin>"
infile = sys.stdin
else:
displayname = filename
infile = open(filename)
....
print "Processing", displayname
However, alternatives are
infile = sys.stdin if filename = "-" else open(filename)
...
print "Processing", infile.name
This works because sys.stdin.name == '<stdin>'. But
supppose you had to have "*stdin*". Then the following
works too
infile, displayname = sys.stdin, "*stdin*" if filename == "-" else
open(filename), filename
Err, but this may need some parens as well for precedence.
infile, displayname = (sys.stdin, "*stdin*") if filename == "-" else
(open(filename), filename)
Do you consider this a use or misuse of the if/else expression?
I happen to think it's somewhat harder to understand then
if filename == "-":
displayname = "*stdin*"
infile = sys.stdin
else:
displayname = filename
infile = open(filename)
or even the more terse
if filename == "-":
displayname, infile = "*stdin*", sys.stdin
else:
displayname, infile = filename, open(filename)
> Of course, I don't consider this argument to be proof. There isn't
> going to be any proof in this discussion, because the whole question
> is *always* about which of two equivalent forms to prefer.
Yep.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list